Compare commits

..
Author SHA1 Message Date
github-actions[bot]andgithub-actions[bot] 736b45ac8e Version Packages (#1211)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-06-23 10:33:33 -07:00
Nacho Iacovino b5e1d3bb2b [React] Add useSmartWalletsForAddress hook (#1230) 2023-06-23 12:00:37 +00:00
Jonas Daniels 6816219ac1 [chains] - add/update chains (#1229) 2023-06-22 23:57:03 +00:00
Nacho Iacovino 48065bcd91 [SDK] Accept string in shared metadata (#1222) 2023-06-22 23:39:34 +00:00
Manan Tank a388d07a3d Add Magic Connect support (#1226) 2023-06-22 20:28:04 +00:00
Nacho Iacovino 483e2b9109 [SDK] Fix namespace for platformFees (#1225) 2023-06-22 19:24:04 +00:00
Nacho Iacovino f7f4f20737 [React + SDK] Better return type for get shared metadata (#1224) 2023-06-22 18:46:57 +00:00
Joaquim Verges 6aa6f7e0bd [SDK] fix maxId in getAll for Open Edition contracts (#1223) 2023-06-22 03:42:24 +00:00
Nacho IacovinoandJonas Daniels d4d9550713 [React + SDK] Add get shared metadata (#1218)
Co-authored-by: Jonas Daniels <[email protected]>
2023-06-22 01:56:48 +00:00
iketw 3cb298ac4b [RN/Wallets] Fix Coinbase Wallet connection rejection error (#1220) 2023-06-22 00:29:24 +00:00
Joaquim Verges c747670b98 [SDK] Fix nextTokenIdToMint for open edition (#1219) 2023-06-22 00:08:55 +00:00
Joaquim Verges c08e6ba988 [SDK] Fix claim counts for Open Edition contracts (#1216) 2023-06-21 23:49:27 +00:00
Manan Tank 60fb188943 [react] Fix safeWallet tree-shaking (#1212) 2023-06-21 20:17:13 +00:00
iketw 1ce8558df4 [Wallets] Fix switchChain in WCV2 connector (#1214) 2023-06-21 16:28:16 +00:00
iketw 3ce5f9a0c3 [RC/Wallets] Improve error messages for wc and auth (#1213) 2023-06-21 15:45:03 +00:00
Kien NgoandManan Tank 3d615a62d0 [SDK] Code abstraction; import/export updates (#1188)
Co-authored-by: Manan Tank <[email protected]>
2023-06-21 14:40:12 +00:00
134 changed files with 12259 additions and 20232 deletions
+7
View File
@@ -1,5 +1,12 @@
# @thirdweb-dev/auth # @thirdweb-dev/auth
## 3.2.2
### Patch Changes
- Updated dependencies [[`3cb298ac`](https://github.com/thirdweb-dev/js/commit/3cb298ac4b04d295899b5ac77c7fc5869ec2f5f2), [`3ce5f9a0`](https://github.com/thirdweb-dev/js/commit/3ce5f9a0c3fc7e99b5abf691a87048ab8475f6b1), [`a388d07a`](https://github.com/thirdweb-dev/js/commit/a388d07a3d449e56dc53fed9600931022f4a15e1), [`1ce8558d`](https://github.com/thirdweb-dev/js/commit/1ce8558df47186bcba5ee8564fdb04583bf115dd), [`60fb1889`](https://github.com/thirdweb-dev/js/commit/60fb18894372f14d9cd815fa9a239926d31bb273)]:
- @thirdweb-dev/wallets@0.3.2
## 3.2.1 ## 3.2.1
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/auth", "name": "@thirdweb-dev/auth",
"version": "3.2.1", "version": "3.2.2",
"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",
"browser": { "browser": {
+6
View File
@@ -1,5 +1,11 @@
# @thirdweb-dev/chains # @thirdweb-dev/chains
## 0.1.23
### Patch Changes
- [#1229](https://github.com/thirdweb-dev/js/pull/1229) [`6816219a`](https://github.com/thirdweb-dev/js/commit/6816219ac13ae571a0c90db6ab389c319bc1f052) Thanks [@jnsdls](https://github.com/jnsdls)! - add/update chains
## 0.1.22 ## 0.1.22
### Patch Changes ### Patch Changes
+36
View File
@@ -0,0 +1,36 @@
import type { Chain } from "../src/types";
export default {
"name": "BRC Chain Mainnet",
"chain": "BRC",
"rpc": [
"https://brc-chain.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://rpc.brcchain.io"
],
"faucets": [
"https://faucet.brcchain.io"
],
"nativeCurrency": {
"name": "BRC Chain mainnet native token",
"symbol": "BRC",
"decimals": 18
},
"infoURL": "https://bridge.brcchain.io",
"shortName": "BRC",
"chainId": 12123,
"networkId": 12123,
"icon": {
"url": "ipfs://QmX8qGX7xoZqYUpHxA85uZwQX2fgbTHvmddE1NfseDyBED",
"width": 512,
"height": 512,
"format": "png"
},
"explorers": [
{
"name": "BRC Chain Explorer",
"url": "https://scan.brcchain.io",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "brc-chain"
} as const satisfies Chain;
+2 -2
View File
@@ -4,7 +4,7 @@ export default {
"chain": "ATH", "chain": "ATH",
"rpc": [ "rpc": [
"https://atheios.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://atheios.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://wallet.atheios.com:8797" "https://rpc.atheios.org/"
], ],
"faucets": [], "faucets": [],
"nativeCurrency": { "nativeCurrency": {
@@ -12,7 +12,7 @@ export default {
"symbol": "ATH", "symbol": "ATH",
"decimals": 18 "decimals": 18
}, },
"infoURL": "https://atheios.com", "infoURL": "https://atheios.org",
"shortName": "ath", "shortName": "ath",
"chainId": 1620, "chainId": 1620,
"networkId": 11235813, "networkId": 11235813,
+2 -1
View File
@@ -11,7 +11,8 @@ export default {
}, },
"rpc": [ "rpc": [
"https://horizen-gobi-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://horizen-gobi-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://gobi-testnet.horizenlabs.io/ethv1" "https://gobi-testnet.horizenlabs.io/ethv1",
"https://rpc.ankr.com/horizen_testnet_evm"
], ],
"features": [ "features": [
{ {
+24
View File
@@ -0,0 +1,24 @@
import type { Chain } from "../src/types";
export default {
"name": "Omega Mainnet",
"chain": "OmegaNetwork",
"shortName": "OmegaNetwork",
"chainId": 408,
"testnet": false,
"icon": {
"format": "png",
"url": "ipfs://bafkreig676zxfhwhcx5bvvvjxedx6ftr2wq4iiznrwm3c6ozrprbc4oxwm",
"height": 512,
"width": 512
},
"rpc": [
"https://omega.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://mainnet-rpc.omtch.com"
],
"nativeCurrency": {
"name": "Omega Network Coin",
"symbol": "OMN",
"decimals": 18
},
"slug": "omega"
} as const satisfies Chain;
+35
View File
@@ -0,0 +1,35 @@
import type { Chain } from "../src/types";
export default {
"name": "opBNB",
"chain": "opBNB",
"shortName": "opBNB",
"chainId": 5611,
"testnet": true,
"nativeCurrency": {
"name": "Testnet bnb",
"symbol": "Tbnb",
"decimals": 18
},
"rpc": [
"https://opbnb.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://opbnb-testnet-rpc.bnbchain.org"
],
"explorers": [
{
"name": "opBNB Scan",
"url": "https://opbnbscan.com/",
"standard": ""
}
],
"faucets": [
"https://opbnb-testnet-bridge.bnbchain.org/"
],
"infoURL": "https://docs.bnbchain.org/",
"icon": {
"url": "ipfs://QmfFvfFsQKby3M32uqr8T55ENBnTHL8bkdeeu6rYVL2n4z/opbnblogo.svg",
"height": 512,
"width": 512,
"format": "svg"
},
"slug": "opbnb"
} as const satisfies Chain;
+12 -12
View File
@@ -4,7 +4,7 @@ export default {
"chain": "ETH", "chain": "ETH",
"rpc": [ "rpc": [
"https://zora.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://zora.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://rpc.zora.co/" "https://rpc.zora.energy/"
], ],
"faucets": [], "faucets": [],
"nativeCurrency": { "nativeCurrency": {
@@ -12,23 +12,23 @@ export default {
"symbol": "ETH", "symbol": "ETH",
"decimals": 18 "decimals": 18
}, },
"infoURL": "https://zora.co",
"shortName": "zora",
"chainId": 7777777,
"networkId": 7777777,
"explorers": [
{
"name": "Zora Network Explorer",
"url": "https://explorer.zora.co",
"standard": "EIP3091"
}
],
"icon": { "icon": {
"url": "ipfs://QmZ6qaRwTPFEZUspwMUjaxC6KhmzcELdRQcQzS3P72Dzts/Vector.svg", "url": "ipfs://QmZ6qaRwTPFEZUspwMUjaxC6KhmzcELdRQcQzS3P72Dzts/Vector.svg",
"height": 512, "height": 512,
"width": 512, "width": 512,
"format": "svg" "format": "svg"
}, },
"infoURL": "https://zora.energy",
"shortName": "zora",
"chainId": 7777777,
"networkId": 7777777,
"explorers": [
{
"name": "Zora Network Explorer",
"url": "https://explorer.zora.energy",
"standard": "EIP3091"
}
],
"testnet": false, "testnet": false,
"slug": "zora" "slug": "zora"
} as const satisfies Chain; } as const satisfies Chain;
+27
View File
@@ -2,6 +2,12 @@ import type { Chain } from "../src/types";
export default { export default {
"name": "Patex", "name": "Patex",
"chain": "ETH", "chain": "ETH",
"icon": {
"url": "ipfs://QmTNTSNn3t5WpSEzQmUYbkxYkBKaH6QahyVdVrRKyPHChr",
"width": 800,
"height": 800,
"format": "png"
},
"rpc": [ "rpc": [
"https://patex.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://patex.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://rpc.patex.io/" "https://rpc.patex.io/"
@@ -12,10 +18,31 @@ export default {
"symbol": "ETH", "symbol": "ETH",
"decimals": 18 "decimals": 18
}, },
"features": [
{
"name": "EIP155"
},
{
"name": "EIP1559"
}
],
"infoURL": "https://patex.io/", "infoURL": "https://patex.io/",
"shortName": "peth", "shortName": "peth",
"chainId": 789, "chainId": 789,
"networkId": 789, "networkId": 789,
"explorers": [
{
"name": "patexscan",
"url": "https://patexscan.io",
"icon": {
"url": "ipfs://QmTNTSNn3t5WpSEzQmUYbkxYkBKaH6QahyVdVrRKyPHChr",
"width": 800,
"height": 800,
"format": "png"
},
"standard": "EIP3091"
}
],
"testnet": false, "testnet": false,
"slug": "patex" "slug": "patex"
} as const satisfies Chain; } as const satisfies Chain;
+15 -19
View File
@@ -1,39 +1,35 @@
import type { Chain } from "../src/types"; import type { Chain } from "../src/types";
export default { export default {
"name": "Shardeum Liberty 2.X", "name": "Shardeum Sphinx DApp 1.X",
"shortName": "Sphinx",
"chain": "Shardeum", "chain": "Shardeum",
"chainId": 8081,
"icon": { "icon": {
"url": "ipfs://Qma1bfuubpepKn7DLDy4NPSKDeT3S4VPCNhu6UmdGrb6YD", "height": 1200,
"width": 609, "width": 1200,
"height": 533, "url": "ipfs://QmQWzHUy4kmk1eGksDREGQL3GWrssdAPBxHt4aKGAFHSfJ",
"format": "png" "format": "png"
}, },
"rpc": [ "rpc": [
"https://shardeum-liberty-2-x.rpc.thirdweb.com/${THIRDWEB_API_KEY}", "https://shardeum-sphinx-dapp-1-x.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://liberty20.shardeum.org/" "https://dapps.shardeum.org/sphinx"
],
"faucets": [
"https://faucet.liberty20.shardeum.org"
], ],
"nativeCurrency": { "nativeCurrency": {
"name": "Shardeum SHM", "name": "Shardeum",
"symbol": "SHM", "symbol": "SHM",
"decimals": 18 "decimals": 18
}, },
"infoURL": "https://docs.shardeum.org/",
"shortName": "Liberty20",
"chainId": 8081,
"networkId": 8081,
"explorers": [ "explorers": [
{ {
"name": "Shardeum Scan", "name": "Shardeum Scan",
"url": "https://explorer-liberty20.shardeum.org", "url": "https://explorer-dapps.shardeum.org",
"standard": "EIP3091" "standard": "EIP3091"
} }
], ],
"redFlags": [ "faucets": [
"reusedChainId" "https://faucet-dapps.shardeum.org/"
], ],
"testnet": false, "infoURL": "https://docs.shardeum.org/",
"slug": "shardeum-liberty-2-x" "testnet": true,
"slug": "shardeum-sphinx-dapp-1-x"
} as const satisfies Chain; } as const satisfies Chain;
+23
View File
@@ -0,0 +1,23 @@
// @ts-check
/** @typedef { import("../../src/types").Chain } Chain */
/** @type {Omit<Chain, "slug">} */
export default {
name: "Omega Mainnet",
chain: "OmegaNetwork",
shortName: "OmegaNetwork",
chainId: 408,
testnet: false,
icon: {
format: "png",
url: "ipfs://bafkreig676zxfhwhcx5bvvvjxedx6ftr2wq4iiznrwm3c6ozrprbc4oxwm",
height: 512,
width: 512,
},
rpc: ["https://mainnet-rpc.omtch.com"],
nativeCurrency: {
name: "Omega Network Coin",
symbol: "OMN",
decimals: 18,
},
};
+32
View File
@@ -0,0 +1,32 @@
// @ts-check
/** @typedef { import("../../src/types").Chain } Chain */
/** @type {Omit<Chain, "slug">} */
export default {
name: "opBNB",
chain: "opBNB",
shortName: "opBNB",
chainId: 5611,
testnet: true,
nativeCurrency: {
name: "Testnet bnb",
symbol: "Tbnb",
decimals: 18,
},
rpc: ["https://opbnb-testnet-rpc.bnbchain.org"],
explorers: [
{
name: "opBNB Scan",
url: "https://opbnbscan.com/",
standard: "",
},
],
faucets: ["https://opbnb-testnet-bridge.bnbchain.org/"],
infoURL: "https://docs.bnbchain.org/",
icon: {
url: "ipfs://QmfFvfFsQKby3M32uqr8T55ENBnTHL8bkdeeu6rYVL2n4z/opbnblogo.svg",
height: 512,
width: 512,
format: "svg",
},
};
+32
View File
@@ -0,0 +1,32 @@
// @ts-check
/** @typedef { import("../../src/types").Chain } Chain */
/** @type {Omit<Chain, "slug">} */
export default {
name: "Shardeum Sphinx DApp 1.X",
shortName: "Sphinx",
chain: "Shardeum",
chainId: 8081,
icon: {
height: 1200,
width: 1200,
url: "ipfs://QmQWzHUy4kmk1eGksDREGQL3GWrssdAPBxHt4aKGAFHSfJ",
format: "png",
},
rpc: ["https://dapps.shardeum.org/sphinx"],
nativeCurrency: {
name: "Shardeum",
symbol: "SHM",
decimals: 18,
},
explorers: [
{
name: "Shardeum Scan",
url: "https://explorer-dapps.shardeum.org",
standard: "EIP3091",
},
],
faucets: ["https://faucet-dapps.shardeum.org/"],
infoURL: "https://docs.shardeum.org/",
testnet: true,
};
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/chains", "name": "@thirdweb-dev/chains",
"version": "0.1.22", "version": "0.1.23",
"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",
"browser": { "browser": {
File diff suppressed because one or more lines are too long
+8
View File
@@ -1,5 +1,13 @@
# thirdweb # thirdweb
## 0.10.25
### Patch Changes
- Updated dependencies [[`6816219a`](https://github.com/thirdweb-dev/js/commit/6816219ac13ae571a0c90db6ab389c319bc1f052), [`48065bcd`](https://github.com/thirdweb-dev/js/commit/48065bcd91c13e1f44d54343b5c6c2646b9e86e4), [`6aa6f7e0`](https://github.com/thirdweb-dev/js/commit/6aa6f7e0bd2313e2e1ad96dd41aad91e6694d380), [`f7f4f207`](https://github.com/thirdweb-dev/js/commit/f7f4f20737ac5d78424ca9c91220f00b85adde6b), [`d4d95507`](https://github.com/thirdweb-dev/js/commit/d4d95507130b2b5408bfaa73ef3b708ca00c773e), [`483e2b91`](https://github.com/thirdweb-dev/js/commit/483e2b910934d75276a68bae64d04c47cd7d57e3), [`c08e6ba9`](https://github.com/thirdweb-dev/js/commit/c08e6ba988ad97aa27d5868cec8abe3498d07a0a), [`3d615a62`](https://github.com/thirdweb-dev/js/commit/3d615a62d0a6801f6fb0e63f9b95c2f98446add1)]:
- @thirdweb-dev/chains@0.1.23
- @thirdweb-dev/sdk@3.10.24
## 0.10.24 ## 0.10.24
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "thirdweb", "name": "thirdweb",
"main": "dist/cli/index.js", "main": "dist/cli/index.js",
"version": "0.10.24", "version": "0.10.25",
"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",
+1 -1
View File
@@ -10,7 +10,7 @@
"license": "Apache-2.0", "license": "Apache-2.0",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/contracts-js", "repository": "https://github.com/thirdweb-dev/js/tree/main/packages/contracts-js",
"dependencies": { "dependencies": {
"@thirdweb-dev/contracts": "3.5.7" "@thirdweb-dev/contracts": "3.5.8"
}, },
"devDependencies": { "devDependencies": {
"@babel/preset-env": "^7.18.10", "@babel/preset-env": "^7.18.10",
+1 -1
View File
@@ -17,7 +17,7 @@ module.exports = {
// import rules // import rules
"import/first": "error", "import/first": "error",
"import/newline-after-import": "error", "import/newline-after-import": "error",
"import/no-cycle": "warn", "import/no-cycle": "error",
"import/no-useless-path-segments": "error", "import/no-useless-path-segments": "error",
//eslint //eslint
+17
View File
@@ -1,5 +1,22 @@
# @thirdweb-dev/react-core # @thirdweb-dev/react-core
## 3.14.2
### Patch Changes
- [#1230](https://github.com/thirdweb-dev/js/pull/1230) [`b5e1d3bb`](https://github.com/thirdweb-dev/js/commit/b5e1d3bb2b82785d6d3e5c899d27691bdb638625) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Add useSmartWalletsForAddress hook
- [#1224](https://github.com/thirdweb-dev/js/pull/1224) [`f7f4f207`](https://github.com/thirdweb-dev/js/commit/f7f4f20737ac5d78424ca9c91220f00b85adde6b) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Better return type for get shared metadata
- [#1213](https://github.com/thirdweb-dev/js/pull/1213) [`3ce5f9a0`](https://github.com/thirdweb-dev/js/commit/3ce5f9a0c3fc7e99b5abf691a87048ab8475f6b1) Thanks [@iketw](https://github.com/iketw)! - [ReactCore/Wallets] Improve error messages for wc and auth
- [#1218](https://github.com/thirdweb-dev/js/pull/1218) [`d4d95507`](https://github.com/thirdweb-dev/js/commit/d4d95507130b2b5408bfaa73ef3b708ca00c773e) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Add get for shared metadata
- Updated dependencies [[`6816219a`](https://github.com/thirdweb-dev/js/commit/6816219ac13ae571a0c90db6ab389c319bc1f052), [`48065bcd`](https://github.com/thirdweb-dev/js/commit/48065bcd91c13e1f44d54343b5c6c2646b9e86e4), [`3cb298ac`](https://github.com/thirdweb-dev/js/commit/3cb298ac4b04d295899b5ac77c7fc5869ec2f5f2), [`6aa6f7e0`](https://github.com/thirdweb-dev/js/commit/6aa6f7e0bd2313e2e1ad96dd41aad91e6694d380), [`f7f4f207`](https://github.com/thirdweb-dev/js/commit/f7f4f20737ac5d78424ca9c91220f00b85adde6b), [`3ce5f9a0`](https://github.com/thirdweb-dev/js/commit/3ce5f9a0c3fc7e99b5abf691a87048ab8475f6b1), [`d4d95507`](https://github.com/thirdweb-dev/js/commit/d4d95507130b2b5408bfaa73ef3b708ca00c773e), [`a388d07a`](https://github.com/thirdweb-dev/js/commit/a388d07a3d449e56dc53fed9600931022f4a15e1), [`1ce8558d`](https://github.com/thirdweb-dev/js/commit/1ce8558df47186bcba5ee8564fdb04583bf115dd), [`483e2b91`](https://github.com/thirdweb-dev/js/commit/483e2b910934d75276a68bae64d04c47cd7d57e3), [`c08e6ba9`](https://github.com/thirdweb-dev/js/commit/c08e6ba988ad97aa27d5868cec8abe3498d07a0a), [`60fb1889`](https://github.com/thirdweb-dev/js/commit/60fb18894372f14d9cd815fa9a239926d31bb273), [`3d615a62`](https://github.com/thirdweb-dev/js/commit/3d615a62d0a6801f6fb0e63f9b95c2f98446add1)]:
- @thirdweb-dev/chains@0.1.23
- @thirdweb-dev/sdk@3.10.24
- @thirdweb-dev/wallets@0.3.2
## 3.14.1 ## 3.14.1
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/react-core", "name": "@thirdweb-dev/react-core",
"version": "3.14.1", "version": "3.14.2",
"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",
@@ -52,7 +52,7 @@ function ChangeActiveWalletOnAccountSwitch() {
try { try {
await switchAccount(data.address); await switchAccount(data.address);
} catch (err) { } catch (err) {
console.warn( console.debug(
`[Auth] Failed to switch account to ${data.address} with error:\n`, `[Auth] Failed to switch account to ${data.address} with error:\n`,
err, err,
); );
@@ -63,7 +63,7 @@ function ChangeActiveWalletOnAccountSwitch() {
try { try {
await logout(); await logout();
} catch (err) { } catch (err) {
console.warn(`[Auth] Failed to logout with error:\n`, err); console.debug(`[Auth] Failed to logout with error:\n`, err);
} }
}; };
+39 -4
View File
@@ -24,6 +24,7 @@ import {
useMutation, useMutation,
UseMutationResult, UseMutationResult,
useQueryClient, useQueryClient,
UseQueryResult,
} from "@tanstack/react-query"; } from "@tanstack/react-query";
import { Erc1155, QueryAllParams, NFT } from "@thirdweb-dev/sdk"; import { Erc1155, QueryAllParams, NFT } from "@thirdweb-dev/sdk";
import { BigNumber, BigNumberish, providers } from "ethers"; import { BigNumber, BigNumberish, providers } from "ethers";
@@ -319,6 +320,44 @@ export function useNFTBalance(
); );
} }
/**
* Get the shared metadata of an Open Edition NFT contract
*
* @example
* ```javascript
* const { data: sharedMetadata, isLoading, error } = useSharedMetadata(contract);
* ```
*
* @param contract - an instance of a {@link NFTContract}
* @returns a response object that includes the shared metadata of the contract
* @twfeature ERC721SharedMetadata
* @see {@link https://portal.thirdweb.com/react/react.usesharedmetadata?utm_source=sdk | Documentation}
* @beta
*/
export function useSharedMetadata(
contract: RequiredParam<NFTContract>,
): UseQueryResult<BasicNFTInput | undefined> {
const contractAddress = contract?.getAddress();
const { erc721 } = getErcs(contract);
return useQueryWithNetwork(
cacheKeys.contract.nft.sharedMetadata.get(contractAddress),
() => {
requiredParamInvariant(contract, "No Contract instance provided");
if (erc721) {
invariant(
erc721.sharedMetadata.get,
"Contract instance does not support sharedMetadata.get",
);
return erc721.sharedMetadata.get();
}
invariant(false, "Unknown NFT type");
},
{
enabled: !!contract,
},
);
}
/** **********************/ /** **********************/
/** WRITE HOOKS **/ /** WRITE HOOKS **/
/** **********************/ /** **********************/
@@ -605,10 +644,6 @@ export function useAirdropNFT(contract: Erc1155) {
); );
} }
/** **********************/
/** WRITE HOOKS **/
/** **********************/
/** /**
* Burn an NFT * Burn an NFT
* *
@@ -15,7 +15,7 @@ import {
UseQueryResult, UseQueryResult,
} from "@tanstack/react-query"; } from "@tanstack/react-query";
import type { import type {
AccountEvent, SmartContract, AccountEvent, AddressOrEns, SmartContract,
} from "@thirdweb-dev/sdk"; } from "@thirdweb-dev/sdk";
import type { BytesLike } from "ethers"; import type { BytesLike } from "ethers";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
@@ -58,6 +58,39 @@ export function useSmartWallets(
); );
} }
/**
* Get all wallets associated with the provided address
*
* @example
* ```javascript
* const { data: smartWalletsForAddress, isLoading, error } = useSmartWalletsForAddress(contract, "{{wallet_address}}");
* ```
*
* @param contract - an instance of a smart wallet factory contract
* @returns a response object that includes an array of all smart wallets associated with the adress
* @twfeature SmartWalletFactory
* @see {@link https://portal.thirdweb.com/react/react.usesmartwalletsforaddress?utm_source=sdk | Documentation}
* @beta
*/
export function useSmartWalletsForAddress(
contract: RequiredParam<SmartContract>,
address: AddressOrEns,
): UseQueryResult<string[]> {
const contractAddress = contract?.getAddress();
return useQueryWithNetwork(
cacheKeys.contract.smartWalletFactory.getAllForAddress(contractAddress, address),
() => {
requiredParamInvariant(contract, "No Contract instance provided");
invariant(
contract.smartWalletFactory.getAssociatedWallets,
"Contract instance does not support contract.smartWalletFactory.getAssociatedWallets",
);
return contract.smartWalletFactory.getAssociatedWallets(address);
},
{ enabled: !!contract },
);
}
/** /**
* Check if a smart wallet has been deployed for the given admin * Check if a smart wallet has been deployed for the given admin
* *
+2
View File
@@ -167,6 +167,7 @@ export {
useTransferNFT, useTransferNFT,
useAirdropNFT, useAirdropNFT,
useBurnNFT, useBurnNFT,
useSharedMetadata,
useSetSharedMetadata, useSetSharedMetadata,
} from "./hooks/async/nft"; } from "./hooks/async/nft";
@@ -198,6 +199,7 @@ export {
useIsSmartWalletDeployed, useIsSmartWalletDeployed,
useSmartWallets, useSmartWallets,
useCreateSmartWallet, useCreateSmartWallet,
useSmartWalletsForAddress,
} from "./hooks/async/smart-wallet-factory"; } from "./hooks/async/smart-wallet-factory";
// thirdweb hooks (work as long as at least `<ThirdwebSdkProvider>` is used) // thirdweb hooks (work as long as at least `<ThirdwebSdkProvider>` is used)
@@ -123,6 +123,8 @@ export const cacheKeys = {
createContractCacheKey(contractAddress, ["smartWalletFactory"]), createContractCacheKey(contractAddress, ["smartWalletFactory"]),
isSmartWalletDeployed: (contractAdress: RequiredParam<ContractAddress>, admin: RequiredParam<string>) => isSmartWalletDeployed: (contractAdress: RequiredParam<ContractAddress>, admin: RequiredParam<string>) =>
createContractCacheKey(contractAdress, ["isSmartWalletDeployed", admin]), createContractCacheKey(contractAdress, ["isSmartWalletDeployed", admin]),
getAllForAddress: (contractAdress: RequiredParam<ContractAddress>, address: RequiredParam<string>) =>
createContractCacheKey(contractAdress, ["getAllForAddress", address]),
}, },
app: { app: {
@@ -190,6 +192,14 @@ export const cacheKeys = {
]), ]),
}, },
}, },
sharedMetadata: {
get: (
contractAddress: RequiredParam<ContractAddress>,
) =>
createContractCacheKey(
contractAddress
),
},
drop: { drop: {
getAllUnclaimed: ( getAllUnclaimed: (
contractAddress: RequiredParam<ContractAddress>, contractAddress: RequiredParam<ContractAddress>,
@@ -1,5 +1,7 @@
# @thirdweb-dev/react-native-compat # @thirdweb-dev/react-native-compat
## 0.2.21
## 0.2.20 ## 0.2.20
## 0.2.19 ## 0.2.19
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "@thirdweb-dev/react-native-compat", "name": "@thirdweb-dev/react-native-compat",
"description": "Shims for Thirdweb in React Native Projects", "description": "Shims for Thirdweb in React Native Projects",
"version": "0.2.20", "version": "0.2.21",
"author": "thirdweb eng <[email protected]>", "author": "thirdweb eng <[email protected]>",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native-compat", "repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native-compat",
"license": "Apache-2.0", "license": "Apache-2.0",
+14
View File
@@ -1,5 +1,19 @@
# @thirdweb-dev/react-native # @thirdweb-dev/react-native
## 0.2.21
### Patch Changes
- [#1220](https://github.com/thirdweb-dev/js/pull/1220) [`3cb298ac`](https://github.com/thirdweb-dev/js/commit/3cb298ac4b04d295899b5ac77c7fc5869ec2f5f2) Thanks [@iketw](https://github.com/iketw)! - [RN/Wallets] Fix Coinbase wallet connection rejection error
Unhandled Rejections: We were rethrowing an error in an async function (connect) without any catch block to handle it. We were getting an Unhandled Promise Rejection, which lead to a crash in React Native when rejecting a connection from the Coinbase Wallet.
- Updated dependencies [[`6816219a`](https://github.com/thirdweb-dev/js/commit/6816219ac13ae571a0c90db6ab389c319bc1f052), [`48065bcd`](https://github.com/thirdweb-dev/js/commit/48065bcd91c13e1f44d54343b5c6c2646b9e86e4), [`3cb298ac`](https://github.com/thirdweb-dev/js/commit/3cb298ac4b04d295899b5ac77c7fc5869ec2f5f2), [`b5e1d3bb`](https://github.com/thirdweb-dev/js/commit/b5e1d3bb2b82785d6d3e5c899d27691bdb638625), [`6aa6f7e0`](https://github.com/thirdweb-dev/js/commit/6aa6f7e0bd2313e2e1ad96dd41aad91e6694d380), [`f7f4f207`](https://github.com/thirdweb-dev/js/commit/f7f4f20737ac5d78424ca9c91220f00b85adde6b), [`3ce5f9a0`](https://github.com/thirdweb-dev/js/commit/3ce5f9a0c3fc7e99b5abf691a87048ab8475f6b1), [`d4d95507`](https://github.com/thirdweb-dev/js/commit/d4d95507130b2b5408bfaa73ef3b708ca00c773e), [`a388d07a`](https://github.com/thirdweb-dev/js/commit/a388d07a3d449e56dc53fed9600931022f4a15e1), [`1ce8558d`](https://github.com/thirdweb-dev/js/commit/1ce8558df47186bcba5ee8564fdb04583bf115dd), [`483e2b91`](https://github.com/thirdweb-dev/js/commit/483e2b910934d75276a68bae64d04c47cd7d57e3), [`c08e6ba9`](https://github.com/thirdweb-dev/js/commit/c08e6ba988ad97aa27d5868cec8abe3498d07a0a), [`60fb1889`](https://github.com/thirdweb-dev/js/commit/60fb18894372f14d9cd815fa9a239926d31bb273), [`3d615a62`](https://github.com/thirdweb-dev/js/commit/3d615a62d0a6801f6fb0e63f9b95c2f98446add1)]:
- @thirdweb-dev/chains@0.1.23
- @thirdweb-dev/sdk@3.10.24
- @thirdweb-dev/wallets@0.3.2
- @thirdweb-dev/react-core@3.14.2
## 0.2.20 ## 0.2.20
### Patch Changes ### Patch Changes
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/react-native", "name": "@thirdweb-dev/react-native",
"version": "0.2.20", "version": "0.2.21",
"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",
@@ -24,7 +24,7 @@
"android" "android"
], ],
"dependencies": { "dependencies": {
"@coinbase/wallet-mobile-sdk": "^1.0.4", "@coinbase/wallet-mobile-sdk": "1.0.6",
"@magic-sdk/provider": "17.2.0", "@magic-sdk/provider": "17.2.0",
"@magic-sdk/react-native-bare": "^18.3.0", "@magic-sdk/react-native-bare": "^18.3.0",
"@shopify/restyle": "^2.4.1", "@shopify/restyle": "^2.4.1",
@@ -39,13 +39,13 @@ export const ConnectWalletFlow = () => {
const connectActiveWallet = useCallback( const connectActiveWallet = useCallback(
async (wallet: WalletConfig, data?: any) => { async (wallet: WalletConfig, data?: any) => {
setIsConnecting(true); setIsConnecting(true);
connect(wallet, { ...data }) try {
.catch((error) => { await connect(wallet, { ...data });
console.error("Error connecting to the wallet", error); } catch (error) {
}) console.error("Error connecting to the wallet", error);
.finally(() => { } finally {
onClose(true); onClose(true);
}); }
}, },
[connect, onClose], [connect, onClose],
); );
@@ -72,10 +72,10 @@ export class CoinbaseWalletConnector extends WagmiConnector<
this.emit("message", { type: "connecting" }); this.emit("message", { type: "connecting" });
const account = (await provider.request({ const accounts: string[] = await provider.request({
method: "eth_requestAccounts", method: "eth_requestAccounts",
params: [], params: [],
})) as Address; });
// Switch to chain if provided // Switch to chain if provided
let id = await this.getChainId(); let id = await this.getChainId();
let unsupported = this.isChainUnsupported(id); let unsupported = this.isChainUnsupported(id);
@@ -93,7 +93,7 @@ export class CoinbaseWalletConnector extends WagmiConnector<
} }
return { return {
account, account: accounts[0],
chain: { id, unsupported }, chain: { id, unsupported },
provider: new providers.Web3Provider( provider: new providers.Web3Provider(
provider as unknown as providers.ExternalProvider, provider as unknown as providers.ExternalProvider,
+12
View File
@@ -1,5 +1,17 @@
# @thirdweb-dev/react # @thirdweb-dev/react
## 3.14.2
### Patch Changes
- [#1226](https://github.com/thirdweb-dev/js/pull/1226) [`a388d07a`](https://github.com/thirdweb-dev/js/commit/a388d07a3d449e56dc53fed9600931022f4a15e1) Thanks [@MananTank](https://github.com/MananTank)! - Add Magic Connect support
- Updated dependencies [[`6816219a`](https://github.com/thirdweb-dev/js/commit/6816219ac13ae571a0c90db6ab389c319bc1f052), [`48065bcd`](https://github.com/thirdweb-dev/js/commit/48065bcd91c13e1f44d54343b5c6c2646b9e86e4), [`3cb298ac`](https://github.com/thirdweb-dev/js/commit/3cb298ac4b04d295899b5ac77c7fc5869ec2f5f2), [`b5e1d3bb`](https://github.com/thirdweb-dev/js/commit/b5e1d3bb2b82785d6d3e5c899d27691bdb638625), [`6aa6f7e0`](https://github.com/thirdweb-dev/js/commit/6aa6f7e0bd2313e2e1ad96dd41aad91e6694d380), [`f7f4f207`](https://github.com/thirdweb-dev/js/commit/f7f4f20737ac5d78424ca9c91220f00b85adde6b), [`3ce5f9a0`](https://github.com/thirdweb-dev/js/commit/3ce5f9a0c3fc7e99b5abf691a87048ab8475f6b1), [`d4d95507`](https://github.com/thirdweb-dev/js/commit/d4d95507130b2b5408bfaa73ef3b708ca00c773e), [`a388d07a`](https://github.com/thirdweb-dev/js/commit/a388d07a3d449e56dc53fed9600931022f4a15e1), [`1ce8558d`](https://github.com/thirdweb-dev/js/commit/1ce8558df47186bcba5ee8564fdb04583bf115dd), [`483e2b91`](https://github.com/thirdweb-dev/js/commit/483e2b910934d75276a68bae64d04c47cd7d57e3), [`c08e6ba9`](https://github.com/thirdweb-dev/js/commit/c08e6ba988ad97aa27d5868cec8abe3498d07a0a), [`60fb1889`](https://github.com/thirdweb-dev/js/commit/60fb18894372f14d9cd815fa9a239926d31bb273), [`3d615a62`](https://github.com/thirdweb-dev/js/commit/3d615a62d0a6801f6fb0e63f9b95c2f98446add1)]:
- @thirdweb-dev/chains@0.1.23
- @thirdweb-dev/sdk@3.10.24
- @thirdweb-dev/wallets@0.3.2
- @thirdweb-dev/react-core@3.14.2
## 3.14.1 ## 3.14.1
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/react", "name": "@thirdweb-dev/react",
"version": "3.14.1", "version": "3.14.2",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react", "repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react",
"author": "thirdweb eng <[email protected]>", "author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0", "license": "Apache-2.0",
@@ -14,21 +14,24 @@ import { InputSelectionUI } from "../InputSelectionUI";
export function magicLink( export function magicLink(
config: MagicLinkAdditionalOptions, config: MagicLinkAdditionalOptions,
): ConfiguredMagicLinkWallet { ): ConfiguredMagicLinkWallet {
const selectUI = (props: SelectUIProps<MagicLink>) => (
<MagicSelectionUI
{...props}
emailLogin={config.emailLogin !== false}
smsLogin={config.smsLogin !== false}
/>
);
return { return {
id: MagicLink.id, id: MagicLink.id,
meta: MagicLink.meta, meta: MagicLink.meta,
create: (options: WalletOptions) => create: (options: WalletOptions) =>
new MagicLink({ ...options, ...config }), new MagicLink({ ...options, ...config }),
connectUI: MagicConnectionUI, connectUI(props) {
selectUI(props) { return <MagicConnectionUI {...props} type={config.type || "auth"} />;
return (
<MagicSelectionUI
{...props}
emailLogin={config.emailLogin !== false}
smsLogin={config.smsLogin !== false}
/>
);
}, },
// select UI only for auth
selectUI: config.type === "connect" ? undefined : selectUI,
isInstalled() { isInstalled() {
return false; return false;
}, },
@@ -101,13 +104,9 @@ const MagicSelectionUI: React.FC<
); );
}; };
const MagicConnectionUI: React.FC<ConnectUIProps<MagicLink>> = ({ const MagicConnectionUI: React.FC<
close, ConnectUIProps<MagicLink> & { type: "auth" | "connect" }
walletConfig, > = ({ close, walletConfig, open, selectionData, supportedWallets, type }) => {
open,
selectionData,
supportedWallets,
}) => {
const connectPrompted = useRef(false); const connectPrompted = useRef(false);
const singleWallet = supportedWallets.length === 1; const singleWallet = supportedWallets.length === 1;
const connect = useConnect(); const connect = useConnect();
@@ -117,14 +116,20 @@ const MagicConnectionUI: React.FC<ConnectUIProps<MagicLink>> = ({
return; return;
} }
connectPrompted.current = true; connectPrompted.current = true;
const isEmail = (selectionData as string).includes("@"); const isEmail = selectionData
? (selectionData as string).includes("@")
: false;
(async () => { (async () => {
close(); close();
try { try {
await connect( await connect(
walletConfig, walletConfig,
isEmail ? { email: selectionData } : { phoneNumber: selectionData }, type === "connect"
? {}
: isEmail
? { email: selectionData }
: { phoneNumber: selectionData },
); );
} catch (e) { } catch (e) {
if (!singleWallet) { if (!singleWallet) {
@@ -133,7 +138,7 @@ const MagicConnectionUI: React.FC<ConnectUIProps<MagicLink>> = ({
console.error(e); console.error(e);
} }
})(); })();
}, [connect, selectionData, walletConfig, close, open, singleWallet]); }, [connect, selectionData, walletConfig, close, open, singleWallet, type]);
return ( return (
<Flex <Flex
+13
View File
@@ -4,6 +4,19 @@ module.exports = {
plugins: ["better-tree-shaking"], plugins: ["better-tree-shaking"],
rules: { rules: {
"better-tree-shaking/no-top-level-side-effects": "error", "better-tree-shaking/no-top-level-side-effects": "error",
"no-restricted-imports": [
"error",
{
paths: [
{
name: "ethers",
importNames: ["ethers"],
message:
"Do not import entire ethers object, Use named imports instead.",
},
],
},
],
}, },
// allow all imports from within tests // allow all imports from within tests
overrides: [ overrides: [
+21
View File
@@ -1,5 +1,26 @@
# @thirdweb-dev/sdk # @thirdweb-dev/sdk
## 3.10.24
### Patch Changes
- [#1222](https://github.com/thirdweb-dev/js/pull/1222) [`48065bcd`](https://github.com/thirdweb-dev/js/commit/48065bcd91c13e1f44d54343b5c6c2646b9e86e4) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Accept string for image/animation_url on shared metadata
- [#1223](https://github.com/thirdweb-dev/js/pull/1223) [`6aa6f7e0`](https://github.com/thirdweb-dev/js/commit/6aa6f7e0bd2313e2e1ad96dd41aad91e6694d380) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - fix maxId in getAll for Open Edition contracts
- [#1224](https://github.com/thirdweb-dev/js/pull/1224) [`f7f4f207`](https://github.com/thirdweb-dev/js/commit/f7f4f20737ac5d78424ca9c91220f00b85adde6b) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Better return type for get shared metadata
- [#1218](https://github.com/thirdweb-dev/js/pull/1218) [`d4d95507`](https://github.com/thirdweb-dev/js/commit/d4d95507130b2b5408bfaa73ef3b708ca00c773e) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Add get for shared metadata
- [#1225](https://github.com/thirdweb-dev/js/pull/1225) [`483e2b91`](https://github.com/thirdweb-dev/js/commit/483e2b910934d75276a68bae64d04c47cd7d57e3) Thanks [@nachoiacovino](https://github.com/nachoiacovino)! - Fix namespace for platform fees
- [#1216](https://github.com/thirdweb-dev/js/pull/1216) [`c08e6ba9`](https://github.com/thirdweb-dev/js/commit/c08e6ba988ad97aa27d5868cec8abe3498d07a0a) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix claim counts for Open Edition contracts
- [#1188](https://github.com/thirdweb-dev/js/pull/1188) [`3d615a62`](https://github.com/thirdweb-dev/js/commit/3d615a62d0a6801f6fb0e63f9b95c2f98446add1) Thanks [@kienngo98](https://github.com/kienngo98)! - Abstract duplicated code; treeshake ethers.js imports
- Updated dependencies [[`6816219a`](https://github.com/thirdweb-dev/js/commit/6816219ac13ae571a0c90db6ab389c319bc1f052)]:
- @thirdweb-dev/chains@0.1.23
## 3.10.23 ## 3.10.23
### Patch Changes ### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@thirdweb-dev/sdk", "name": "@thirdweb-dev/sdk",
"version": "3.10.23", "version": "3.10.24",
"description": "The main thirdweb SDK.", "description": "The main thirdweb SDK.",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk", "repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk",
"license": "Apache-2.0", "license": "Apache-2.0",
@@ -1,4 +1,4 @@
import { BytesLike, ethers } from "ethers"; import { type BytesLike, utils } from "ethers";
import { getSaltHash } from "./getSaltHash"; import { getSaltHash } from "./getSaltHash";
/** /**
@@ -15,27 +15,27 @@ export function computeDeploymentAddress(
create2FactoryAddress: string, create2FactoryAddress: string,
salt?: string, salt?: string,
): string { ): string {
const saltHash = salt ? ethers.utils.id(salt) : getSaltHash(bytecode); const saltHash = salt ? utils.id(salt) : getSaltHash(bytecode);
// 1. create init bytecode hash with contract's bytecode and encoded args // 1. create init bytecode hash with contract's bytecode and encoded args
const initBytecode = ethers.utils.solidityPack( const initBytecode = utils.solidityPack(
["bytes", "bytes"], ["bytes", "bytes"],
[bytecode, encodedArgs], [bytecode, encodedArgs],
); );
// 2. abi-encode pack the deployer address, salt, and bytecode hash // 2. abi-encode pack the deployer address, salt, and bytecode hash
const deployInfoPacked = ethers.utils.solidityPack( const deployInfoPacked = utils.solidityPack(
["bytes1", "address", "bytes32", "bytes32"], ["bytes1", "address", "bytes32", "bytes32"],
[ [
"0xff", "0xff",
create2FactoryAddress, create2FactoryAddress,
saltHash, saltHash,
ethers.utils.solidityKeccak256(["bytes"], [initBytecode]), utils.solidityKeccak256(["bytes"], [initBytecode]),
], ],
); );
// 3. hash the packed deploy info // 3. hash the packed deploy info
const hashedDeployInfo = ethers.utils.solidityKeccak256( const hashedDeployInfo = utils.solidityKeccak256(
["bytes"], ["bytes"],
[deployInfoPacked], [deployInfoPacked],
); );
@@ -12,7 +12,7 @@ import { fetchAndCacheDeployMetadata } from "./fetchAndCacheDeployMetadata";
import { isContractDeployed } from "./isContractDeployed"; import { isContractDeployed } from "./isContractDeployed";
import { getInitBytecodeWithSalt } from "./getInitBytecodeWithSalt"; import { getInitBytecodeWithSalt } from "./getInitBytecodeWithSalt";
import { computeDeploymentAddress } from "./computeDeploymentAddress"; import { computeDeploymentAddress } from "./computeDeploymentAddress";
import { BytesLike, ethers } from "ethers"; import { type BytesLike, utils, constants } from "ethers";
import { getNativeTokenByChainId } from "../../constants/currency"; import { getNativeTokenByChainId } from "../../constants/currency";
import { PreDeployMetadataFetched } from "../../schema/contracts/custom"; import { PreDeployMetadataFetched } from "../../schema/contracts/custom";
import { ConstructorParamMap } from "../../types/any-evm/deploy-data"; import { ConstructorParamMap } from "../../types/any-evm/deploy-data";
@@ -113,7 +113,7 @@ export async function encodeConstructorParamsForImplementation(
); );
let constructorParamTypes = constructorParams.map((p) => { let constructorParamTypes = constructorParams.map((p) => {
if (p.type === "tuple[]") { if (p.type === "tuple[]") {
return ethers.utils.ParamType.from(p); return utils.ParamType.from(p);
} else { } else {
return p.type; return p.type;
} }
@@ -137,7 +137,7 @@ export async function encodeConstructorParamsForImplementation(
let nativeTokenWrapperAddress = let nativeTokenWrapperAddress =
getNativeTokenByChainId(chainId).wrapped.address; getNativeTokenByChainId(chainId).wrapped.address;
if (nativeTokenWrapperAddress === ethers.constants.AddressZero) { if (nativeTokenWrapperAddress === constants.AddressZero) {
const deploymentInfo = await computeDeploymentInfo( const deploymentInfo = await computeDeploymentInfo(
"infra", "infra",
provider, provider,
@@ -194,7 +194,7 @@ export async function encodeConstructorParamsForImplementation(
}), }),
); );
const encodedArgs = ethers.utils.defaultAbiCoder.encode( const encodedArgs = utils.defaultAbiCoder.encode(
constructorParamTypes, constructorParamTypes,
constructorParamValues, constructorParamValues,
); );
@@ -1,4 +1,4 @@
import { BigNumber, ethers } from "ethers"; import { BigNumber, utils } from "ethers";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
export function convertParamValues( export function convertParamValues(
@@ -21,14 +21,14 @@ export function convertParamValues(
} }
if (p === "bytes32") { if (p === "bytes32") {
invariant( invariant(
ethers.utils.isHexString(constructorParamValues[index]), utils.isHexString(constructorParamValues[index]),
`Could not parse bytes32 value. Expected valid hex string but got "${constructorParamValues[index]}".`, `Could not parse bytes32 value. Expected valid hex string but got "${constructorParamValues[index]}".`,
); );
return ethers.utils.hexZeroPad(constructorParamValues[index], 32); return utils.hexZeroPad(constructorParamValues[index], 32);
} }
if (p.startsWith("bytes")) { if (p.startsWith("bytes")) {
invariant( invariant(
ethers.utils.isHexString(constructorParamValues[index]), utils.isHexString(constructorParamValues[index]),
`Could not parse bytes value. Expected valid hex string but got "${constructorParamValues[index]}".`, `Could not parse bytes value. Expected valid hex string but got "${constructorParamValues[index]}".`,
); );
return constructorParamValues[index]; return constructorParamValues[index];
@@ -1,4 +1,4 @@
import { BigNumber, ethers, Signer } from "ethers"; import { BigNumber, type PopulatedTransaction, type Signer } from "ethers";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
import { PrecomputedDeploymentTransaction } from "../../types/any-evm/deploy-data"; import { PrecomputedDeploymentTransaction } from "../../types/any-evm/deploy-data";
import type { DeployOptions } from "../../types/deploy"; import type { DeployOptions } from "../../types/deploy";
@@ -33,7 +33,7 @@ export async function deployContractDeterministic(
`deploying contract via create2 factory at: ${transaction.predictedAddress}`, `deploying contract via create2 factory at: ${transaction.predictedAddress}`,
); );
let tx: ethers.PopulatedTransaction = { let tx: PopulatedTransaction = {
to: transaction.to, to: transaction.to,
data: transaction.data, data: transaction.data,
}; };
@@ -1,4 +1,9 @@
import { BigNumber, BytesLike, ethers, Signer } from "ethers"; import {
BigNumber,
type BytesLike,
type PopulatedTransaction,
type Signer,
} from "ethers";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
import type { DeployOptions } from "../../types/deploy"; import type { DeployOptions } from "../../types/deploy";
import { isContractDeployed } from "./isContractDeployed"; import { isContractDeployed } from "./isContractDeployed";
@@ -10,7 +15,7 @@ import { getInitBytecodeWithSalt } from "./getInitBytecodeWithSalt";
* *
* @public * @public
* *
* @param signer * @param type signer
* @param bytecode * @param bytecode
* @param encodedArgs * @param encodedArgs
* @param create2FactoryAddress * @param create2FactoryAddress
@@ -36,7 +41,7 @@ export async function deployContractDeterministicRaw(
); );
const initBytecodeWithSalt = getInitBytecodeWithSalt(bytecode, encodedArgs); const initBytecodeWithSalt = getInitBytecodeWithSalt(bytecode, encodedArgs);
let tx: ethers.PopulatedTransaction = { let tx: PopulatedTransaction = {
to: create2FactoryAddress, to: create2FactoryAddress,
data: initBytecodeWithSalt, data: initBytecodeWithSalt,
}; };
@@ -1,9 +1,9 @@
import { import {
BigNumber, BigNumber,
PopulatedTransaction, type PopulatedTransaction,
Signer, type Signer,
ethers, utils,
providers, type providers,
} from "ethers"; } from "ethers";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
import { isContractDeployed } from "./isContractDeployed"; import { isContractDeployed } from "./isContractDeployed";
@@ -56,7 +56,7 @@ export async function directDeployDeterministic(
constructorParamTypes, constructorParamTypes,
constructorArgs, constructorArgs,
); );
const encodedArgs = ethers.utils.defaultAbiCoder.encode( const encodedArgs = utils.defaultAbiCoder.encode(
constructorParamTypes, constructorParamTypes,
paramValues, paramValues,
); );
@@ -159,7 +159,7 @@ export async function predictAddressDeterministic(
constructorParamTypes, constructorParamTypes,
constructorArgs, constructorArgs,
); );
const encodedArgs = ethers.utils.defaultAbiCoder.encode( const encodedArgs = utils.defaultAbiCoder.encode(
constructorParamTypes, constructorParamTypes,
paramValues, paramValues,
); );
@@ -1,4 +1,4 @@
import { ethers, Signer } from "ethers"; import { ContractFactory, type Signer } from "ethers";
import { PrecomputedDeploymentTransaction } from "../../types/any-evm/deploy-data"; import { PrecomputedDeploymentTransaction } from "../../types/any-evm/deploy-data";
import type { DeployOptions } from "../../types/deploy"; import type { DeployOptions } from "../../types/deploy";
import { DEPLOYER_ABI, DEPLOYER_BYTECODE } from "./constants"; import { DEPLOYER_ABI, DEPLOYER_BYTECODE } from "./constants";
@@ -18,10 +18,7 @@ export async function deployWithThrowawayDeployer(
const deployTxns = await Promise.all( const deployTxns = await Promise.all(
transactionBatches.map((txBatch) => { transactionBatches.map((txBatch) => {
// Using the deployer contract, send the deploy transactions to common factory with a signer // Using the deployer contract, send the deploy transactions to common factory with a signer
const deployer = new ethers.ContractFactory( const deployer = new ContractFactory(DEPLOYER_ABI, DEPLOYER_BYTECODE)
DEPLOYER_ABI,
DEPLOYER_BYTECODE,
)
.connect(signer) .connect(signer)
.deploy(txBatch); .deploy(txBatch);
@@ -1,8 +1,8 @@
import { ethers } from "ethers"; import { utils } from "ethers";
export function estimateGasForDeploy(initCode: string) { export function estimateGasForDeploy(initCode: string) {
let gasLimit = let gasLimit =
ethers.utils utils
.arrayify(initCode) .arrayify(initCode)
.map((x) => (x === 0 ? 4 : 16)) .map((x) => (x === 0 ? 4 : 16))
.reduce((sum, x) => sum + x) + .reduce((sum, x) => sum + x) +
@@ -1,4 +1,4 @@
import { ethers } from "ethers"; import { utils } from "ethers";
import { KeylessDeploymentInfo } from "../../types/any-evm/deploy-data"; import { KeylessDeploymentInfo } from "../../types/any-evm/deploy-data";
import { SIGNATURE, CREATE2_FACTORY_BYTECODE } from "./constants"; import { SIGNATURE, CREATE2_FACTORY_BYTECODE } from "./constants";
import { getKeylessTxn } from "./getKeylessTxn"; import { getKeylessTxn } from "./getKeylessTxn";
@@ -13,7 +13,7 @@ export function getCreate2FactoryDeploymentInfo(
chainId: number, chainId: number,
gasPrice?: number, gasPrice?: number,
): KeylessDeploymentInfo { ): KeylessDeploymentInfo {
const signature = ethers.utils.joinSignature(SIGNATURE); const signature = utils.joinSignature(SIGNATURE);
const deploymentTransaction = getKeylessTxn( const deploymentTransaction = getKeylessTxn(
{ {
gasPrice: gasPrice ? gasPrice : 100 * 10 ** 9, gasPrice: gasPrice ? gasPrice : 100 * 10 ** 9,
@@ -24,7 +24,7 @@ export function getCreate2FactoryDeploymentInfo(
}, },
signature, signature,
); );
const create2FactoryAddress = ethers.utils.getContractAddress({ const create2FactoryAddress = utils.getContractAddress({
from: deploymentTransaction.signer, from: deploymentTransaction.signer,
nonce: 0, nonce: 0,
}); });
@@ -1,4 +1,4 @@
import { BytesLike, ethers } from "ethers"; import { type BytesLike, utils } from "ethers";
import { getSaltHash } from "./getSaltHash"; import { getSaltHash } from "./getSaltHash";
/** /**
@@ -15,9 +15,9 @@ export function getInitBytecodeWithSalt(
encodedArgs: BytesLike, encodedArgs: BytesLike,
salt?: string, salt?: string,
): string { ): string {
const saltHash = salt ? ethers.utils.id(salt) : getSaltHash(bytecode); const saltHash = salt ? utils.id(salt) : getSaltHash(bytecode);
const initBytecodeWithSalt = ethers.utils.solidityPack( const initBytecodeWithSalt = utils.solidityPack(
["bytes32", "bytes", "bytes"], ["bytes32", "bytes", "bytes"],
[saltHash, bytecode, encodedArgs], [saltHash, bytecode, encodedArgs],
); );
@@ -1,4 +1,4 @@
import { ethers } from "ethers"; import { utils, type UnsignedTransaction } from "ethers";
import { KeylessTransaction } from "../../types/any-evm/deploy-data"; import { KeylessTransaction } from "../../types/any-evm/deploy-data";
/** /**
@@ -9,20 +9,20 @@ import { KeylessTransaction } from "../../types/any-evm/deploy-data";
* @param signature: Signature bytes * @param signature: Signature bytes
*/ */
export function getKeylessTxn( export function getKeylessTxn(
transaction: ethers.UnsignedTransaction, transaction: UnsignedTransaction,
signature: string, signature: string,
): KeylessTransaction { ): KeylessTransaction {
// 1. Create serialized txn string // 1. Create serialized txn string
const digest = ethers.utils.arrayify( const digest = utils.arrayify(
ethers.utils.keccak256(ethers.utils.serializeTransaction(transaction)), utils.keccak256(utils.serializeTransaction(transaction)),
); );
// 2. Determine signer address from custom signature + txn // 2. Determine signer address from custom signature + txn
const signer = ethers.utils.recoverAddress(digest, signature); const signer = utils.recoverAddress(digest, signature);
// 3. Create the signed serialized txn string. // 3. Create the signed serialized txn string.
// To be sent directly to the chain using a provider. // To be sent directly to the chain using a provider.
const signedSerializedTx = ethers.utils.serializeTransaction( const signedSerializedTx = utils.serializeTransaction(
transaction, transaction,
signature, signature,
); );
@@ -1,4 +1,4 @@
import { ethers } from "ethers"; import { utils } from "ethers";
/** /**
* Generate salt for deployment with Create2 * Generate salt for deployment with Create2
@@ -8,9 +8,9 @@ import { ethers } from "ethers";
* @param bytecode: Creation bytecode of the contract to deploy * @param bytecode: Creation bytecode of the contract to deploy
*/ */
export function getSaltHash(bytecode: string): string { export function getSaltHash(bytecode: string): string {
const bytecodeHash = ethers.utils.id(bytecode); const bytecodeHash = utils.id(bytecode);
const salt = `tw.${bytecodeHash}`; const salt = `tw.${bytecodeHash}`;
const saltHash = ethers.utils.id(salt); const saltHash = utils.id(salt);
return saltHash; return saltHash;
} }
@@ -1,5 +1,5 @@
import { Quantity } from "../../../core/schema/shared"; import { Quantity } from "../../../core/schema/shared";
import { ethers } from "ethers"; import { utils, constants } from "ethers";
/** /**
* @internal * @internal
@@ -11,8 +11,8 @@ export function convertQuantityToBigNumber(
tokenDecimals: number, tokenDecimals: number,
) { ) {
if (quantity === "unlimited") { if (quantity === "unlimited") {
return ethers.constants.MaxUint256; return constants.MaxUint256;
} else { } else {
return ethers.utils.parseUnits(quantity, tokenDecimals); return utils.parseUnits(quantity, tokenDecimals);
} }
} }
@@ -1,4 +1,4 @@
import { BigNumberish, ethers } from "ethers"; import { type BigNumberish, constants, utils } from "ethers";
/** /**
* @internal * @internal
@@ -9,9 +9,9 @@ export function convertToReadableQuantity(
bn: BigNumberish, bn: BigNumberish,
tokenDecimals: number, tokenDecimals: number,
) { ) {
if (bn.toString() === ethers.constants.MaxUint256.toString()) { if (bn.toString() === constants.MaxUint256.toString()) {
return "unlimited"; return "unlimited";
} else { } else {
return ethers.utils.formatUnits(bn, tokenDecimals); return utils.formatUnits(bn, tokenDecimals);
} }
} }
@@ -7,13 +7,13 @@ import {
SnapshotFormatVersion, SnapshotFormatVersion,
} from "../sharded-merkle-tree"; } from "../sharded-merkle-tree";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { ethers } from "ethers"; import type { providers } from "ethers";
export async function fetchSnapshotEntryForAddress( export async function fetchSnapshotEntryForAddress(
address: string, address: string,
merkleRoot: string, merkleRoot: string,
merkleMetadata: Record<string, string> | undefined, merkleMetadata: Record<string, string> | undefined,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
snapshotFormatVersion: SnapshotFormatVersion, snapshotFormatVersion: SnapshotFormatVersion,
): Promise<SnapshotEntryWithProof | null> { ): Promise<SnapshotEntryWithProof | null> {
@@ -5,7 +5,7 @@ import type {
} from "../../types/claim-conditions/claim-conditions"; } from "../../types/claim-conditions/claim-conditions";
import { SnapshotFormatVersion } from "../sharded-merkle-tree"; import { SnapshotFormatVersion } from "../sharded-merkle-tree";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, constants, ethers, utils } from "ethers"; import { BigNumber, type BigNumberish, constants, utils } from "ethers";
import { approveErc20Allowance } from "../currency/approveErc20Allowance"; import { approveErc20Allowance } from "../currency/approveErc20Allowance";
import { isNativeToken } from "../currency/isNativeToken"; import { isNativeToken } from "../currency/isNativeToken";
import { normalizePriceValue } from "../currency/normalizePriceValue"; import { normalizePriceValue } from "../currency/normalizePriceValue";
@@ -54,22 +54,19 @@ export async function prepareClaim(
// override only if not default values (unlimited for quantity, zero addr for currency) // override only if not default values (unlimited for quantity, zero addr for currency)
maxClaimable = maxClaimable =
snapshotEntry.maxClaimable === "unlimited" snapshotEntry.maxClaimable === "unlimited"
? ethers.constants.MaxUint256 ? constants.MaxUint256
: ethers.utils.parseUnits( : utils.parseUnits(snapshotEntry.maxClaimable, tokenDecimals);
snapshotEntry.maxClaimable,
tokenDecimals,
);
priceInProof = priceInProof =
snapshotEntry.price === undefined || snapshotEntry.price === undefined ||
snapshotEntry.price === "unlimited" snapshotEntry.price === "unlimited"
? ethers.constants.MaxUint256 ? constants.MaxUint256
: await normalizePriceValue( : await normalizePriceValue(
contractWrapper.getProvider(), contractWrapper.getProvider(),
snapshotEntry.price, snapshotEntry.price,
snapshotEntry.currencyAddress || ethers.constants.AddressZero, snapshotEntry.currencyAddress || constants.AddressZero,
); );
currencyAddressInProof = currencyAddressInProof =
snapshotEntry.currencyAddress || ethers.constants.AddressZero; snapshotEntry.currencyAddress || constants.AddressZero;
} else { } else {
// if no snapshot entry, and it's a v1 format (exclusive allowlist) then address can't claim // if no snapshot entry, and it's a v1 format (exclusive allowlist) then address can't claim
if (snapshotFormatVersion === SnapshotFormatVersion.V1) { if (snapshotFormatVersion === SnapshotFormatVersion.V1) {
@@ -95,19 +92,19 @@ export async function prepareClaim(
// if proof price is unlimited, then we use the price from the claim condition // if proof price is unlimited, then we use the price from the claim condition
// this mimics the contract behavior // this mimics the contract behavior
const pricePerToken = const pricePerToken =
priceInProof.toString() !== ethers.constants.MaxUint256.toString() priceInProof.toString() !== constants.MaxUint256.toString()
? priceInProof ? priceInProof
: activeClaimCondition.price; : activeClaimCondition.price;
// same for currency address // same for currency address
const currencyAddress = const currencyAddress =
currencyAddressInProof !== ethers.constants.AddressZero currencyAddressInProof !== constants.AddressZero
? currencyAddressInProof ? currencyAddressInProof
: activeClaimCondition.currencyAddress; : activeClaimCondition.currencyAddress;
if (pricePerToken.gt(0)) { if (pricePerToken.gt(0)) {
if (isNativeToken(currencyAddress)) { if (isNativeToken(currencyAddress)) {
overrides["value"] = BigNumber.from(pricePerToken) overrides["value"] = BigNumber.from(pricePerToken)
.mul(quantity) .mul(quantity)
.div(ethers.utils.parseUnits("1", tokenDecimals)); .div(utils.parseUnits("1", tokenDecimals));
} else if (checkERC20Allowance) { } else if (checkERC20Allowance) {
await approveErc20Allowance( await approveErc20Allowance(
contractWrapper, contractWrapper,
@@ -13,10 +13,9 @@ import { createSnapshot } from "../snapshots";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { import {
BigNumber, BigNumber,
BigNumberish, type BigNumberish,
constants, constants,
ethers, type providers,
providers,
utils, utils,
} from "ethers"; } from "ethers";
import { normalizePriceValue } from "../currency/normalizePriceValue"; import { normalizePriceValue } from "../currency/normalizePriceValue";
@@ -46,7 +45,7 @@ function compare(a: BigNumberish, b: BigNumberish) {
export async function processSnapshotData( export async function processSnapshotData(
claimConditionInputs: ClaimConditionInput[], claimConditionInputs: ClaimConditionInput[],
tokenDecimals: number, tokenDecimals: number,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
snapshotFormatVersion: SnapshotFormatVersion, snapshotFormatVersion: SnapshotFormatVersion,
) { ) {
@@ -6,7 +6,7 @@ import type {
ClaimConditionInput, ClaimConditionInput,
ClaimCondition, ClaimCondition,
} from "../../types/claim-conditions/claim-conditions"; } from "../../types/claim-conditions/claim-conditions";
import { ethers } from "ethers"; import { utils } from "ethers";
/** /**
* @internal * @internal
@@ -27,7 +27,7 @@ export async function updateExistingClaimConditions(
// merge input with existing claim condition // merge input with existing claim condition
const priceDecimals = existingConditions[index].currencyMetadata.decimals; const priceDecimals = existingConditions[index].currencyMetadata.decimals;
const priceInWei = existingConditions[index].price; const priceInWei = existingConditions[index].price;
const priceInTokens = ethers.utils.formatUnits(priceInWei, priceDecimals); const priceInTokens = utils.formatUnits(priceInWei, priceDecimals);
// merge existing (output format) with incoming (input format) // merge existing (output format) with incoming (input format)
const newConditionParsed = await ClaimConditionInputSchema.parseAsync({ const newConditionParsed = await ClaimConditionInputSchema.parseAsync({
@@ -49,7 +49,7 @@ export async function updateExistingClaimConditions(
} else { } else {
newConditionAtIndex = existingOutput; newConditionAtIndex = existingOutput;
} }
const formattedPrice = ethers.utils.formatUnits( const formattedPrice = utils.formatUnits(
newConditionAtIndex.price, newConditionAtIndex.price,
priceDecimals, priceDecimals,
); );
@@ -1,7 +1,7 @@
import { ContractWrapper } from "../../core/classes/contract-wrapper"; import { ContractWrapper } from "../../core/classes/contract-wrapper";
import type { IERC20 } from "@thirdweb-dev/contracts-js"; import type { IERC20 } from "@thirdweb-dev/contracts-js";
import ERC20Abi from "@thirdweb-dev/contracts-js/dist/abis/IERC20.json"; import ERC20Abi from "@thirdweb-dev/contracts-js/dist/abis/IERC20.json";
import { BigNumber, BigNumberish, ethers } from "ethers"; import { BigNumber, type BigNumberish, utils } from "ethers";
export async function approveErc20Allowance( export async function approveErc20Allowance(
contractToApprove: ContractWrapper<any>, contractToApprove: ContractWrapper<any>,
@@ -23,7 +23,7 @@ export async function approveErc20Allowance(
const allowance = await erc20.readContract.allowance(owner, spender); const allowance = await erc20.readContract.allowance(owner, spender);
const totalPrice = BigNumber.from(price) const totalPrice = BigNumber.from(price)
.mul(BigNumber.from(quantity)) .mul(BigNumber.from(quantity))
.div(ethers.utils.parseUnits("1", tokenDecimals)); .div(utils.parseUnits("1", tokenDecimals));
if (allowance.lt(totalPrice)) { if (allowance.lt(totalPrice)) {
await erc20.sendTransaction("approve", [ await erc20.sendTransaction("approve", [
spender, spender,
+2 -2
View File
@@ -2,7 +2,7 @@ import { SUPPORTED_CHAIN_ID } from "../constants/chains/SUPPORTED_CHAIN_ID";
import { NATIVE_TOKENS } from "../constants/currency"; import { NATIVE_TOKENS } from "../constants/currency";
import { Feature } from "../constants/contract-features"; import { Feature } from "../constants/contract-features";
import { ContractSource } from "../schema/contracts/custom"; import { ContractSource } from "../schema/contracts/custom";
import { BigNumber, BigNumberish, ethers, providers } from "ethers"; import { BigNumber, type BigNumberish, utils, type providers } from "ethers";
/** /**
* Error that may get thrown if IPFS returns nothing for a given uri. * Error that may get thrown if IPFS returns nothing for a given uri.
@@ -320,7 +320,7 @@ export class TransactionError extends Error {
if (info.value && info.value.gt(0)) { if (info.value && info.value.gt(0)) {
errorMessage += withSpaces( errorMessage += withSpaces(
"value", "value",
`${ethers.utils.formatEther(info.value)} ${ `${utils.formatEther(info.value)} ${
NATIVE_TOKENS[info.network.chainId as SUPPORTED_CHAIN_ID]?.symbol || NATIVE_TOKENS[info.network.chainId as SUPPORTED_CHAIN_ID]?.symbol ||
"" ""
}`, }`,
@@ -1,5 +1,5 @@
import { ContractWrapper } from "../../core/classes/contract-wrapper"; import type { ContractWrapper } from "../../core/classes/contract-wrapper";
import { BaseContract } from "ethers"; import type { BaseContract } from "ethers";
/** /**
* @internal * @internal
+8 -2
View File
@@ -21,7 +21,13 @@ import type {
ThirdwebStorage, ThirdwebStorage,
UploadProgressEvent, UploadProgressEvent,
} from "@thirdweb-dev/storage"; } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, Contract, ethers, providers } from "ethers"; import {
BigNumber,
type BigNumberish,
Contract,
utils,
type providers,
} from "ethers";
export const FALLBACK_METADATA = { export const FALLBACK_METADATA = {
name: "Failed to load NFT metadata", name: "Failed to load NFT metadata",
@@ -42,7 +48,7 @@ export async function fetchTokenMetadata(
): Promise<NFTMetadata> { ): Promise<NFTMetadata> {
const parsedUri = tokenUri.replace( const parsedUri = tokenUri.replace(
"{id}", "{id}",
ethers.utils.hexZeroPad(BigNumber.from(tokenId).toHexString(), 32).slice(2), utils.hexZeroPad(BigNumber.from(tokenId).toHexString(), 32).slice(2),
); );
let jsonMetadata; let jsonMetadata;
try { try {
+12 -8
View File
@@ -3,7 +3,14 @@ import {
EIP712StandardDomain, EIP712StandardDomain,
signTypedDataInternal, signTypedDataInternal,
} from "./sign"; } from "./sign";
import { BigNumber, BigNumberish, Contract, ethers, Signer } from "ethers"; import {
BigNumber,
type BigNumberish,
Contract,
utils,
constants,
type Signer,
} from "ethers";
const NAME_ABI = [ const NAME_ABI = [
{ {
@@ -99,14 +106,11 @@ async function getChainDomainSeperator(
name: domain.name, name: domain.name,
version: domain.version, version: domain.version,
verifyingContract: domain.verifyingContract, verifyingContract: domain.verifyingContract,
salt: ethers.utils.hexZeroPad( salt: utils.hexZeroPad(BigNumber.from(domain.chainId).toHexString(), 32),
BigNumber.from(domain.chainId).toHexString(),
32,
),
}; };
if ( if (
ethers.utils._TypedDataEncoder.hashDomain(polygonDomain) === utils._TypedDataEncoder.hashDomain(polygonDomain) ===
contractDomainSeparator contractDomainSeparator
) { ) {
return polygonDomain; return polygonDomain;
@@ -135,7 +139,7 @@ export async function signDAIPermit(
}); });
nonce = nonce || (await getSignerNonce(signer, currencyAddress)).toString(); nonce = nonce || (await getSignerNonce(signer, currencyAddress)).toString();
deadline = deadline || ethers.constants.MaxUint256; deadline = deadline || constants.MaxUint256;
const message = { const message = {
owner, owner,
@@ -190,7 +194,7 @@ export async function signEIP2612Permit(
}); });
nonce = nonce || (await getSignerNonce(signer, currencyAddress)).toString(); nonce = nonce || (await getSignerNonce(signer, currencyAddress)).toString();
deadline = deadline || ethers.constants.MaxUint256; deadline = deadline || constants.MaxUint256;
const message = { const message = {
owner, owner,
@@ -1,5 +1,5 @@
import { Abi } from "../../schema/contracts/custom"; import { Abi } from "../../schema/contracts/custom";
import { ethers } from "ethers"; import { utils } from "ethers";
import { Plugin } from "../../types/plugins"; import { Plugin } from "../../types/plugins";
function getFunctionSignature(fnInputs: any): string { function getFunctionSignature(fnInputs: any): string {
@@ -18,7 +18,7 @@ export function generatePluginFunctions(
pluginAddress: string, pluginAddress: string,
pluginAbi: Abi, pluginAbi: Abi,
): Plugin[] { ): Plugin[] {
const pluginInterface = new ethers.utils.Interface(pluginAbi); const pluginInterface = new utils.Interface(pluginAbi);
const pluginFunctions: Plugin[] = []; const pluginFunctions: Plugin[] = [];
// TODO - filter out common functions like _msgSender(), contractType(), etc. // TODO - filter out common functions like _msgSender(), contractType(), etc.
for (const fnFragment of Object.values(pluginInterface.functions)) { for (const fnFragment of Object.values(pluginInterface.functions)) {
+3 -3
View File
@@ -1,4 +1,4 @@
import { BytesLike, ethers } from "ethers"; import { type BytesLike, utils } from "ethers";
/** /**
* *
@@ -31,7 +31,7 @@ export const ALL_ROLES = /* @__PURE__ */ Object.keys(roleMap) as Role[];
*/ */
export function getRoleHash(role: Role): BytesLike { export function getRoleHash(role: Role): BytesLike {
if (role === "admin") { if (role === "admin") {
return ethers.utils.hexZeroPad([0], 32); return utils.hexZeroPad([0], 32);
} }
return ethers.utils.id(roleMap[role]); return utils.id(roleMap[role]);
} }
@@ -10,7 +10,7 @@ import type { SnapshotInput } from "../types/claim-conditions/claim-conditions";
import { convertQuantityToBigNumber } from "./claim-conditions/convertQuantityToBigNumber"; import { convertQuantityToBigNumber } from "./claim-conditions/convertQuantityToBigNumber";
import { fetchCurrencyMetadata } from "./currency/fetchCurrencyMetadata"; import { fetchCurrencyMetadata } from "./currency/fetchCurrencyMetadata";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { ethers, utils } from "ethers"; import { constants, utils, type providers } from "ethers";
import { MerkleTree } from "merkletreejs"; import { MerkleTree } from "merkletreejs";
import { parseSnapshotInputs } from "./parseSnapshotInputs"; import { parseSnapshotInputs } from "./parseSnapshotInputs";
@@ -105,7 +105,7 @@ export class ShardedMerkleTree {
entry.price || "unlimited", entry.price || "unlimited",
currencyDecimals, currencyDecimals,
), ),
entry.currencyAddress || ethers.constants.AddressZero, entry.currencyAddress || constants.AddressZero,
], ],
); );
} }
@@ -113,7 +113,7 @@ export class ShardedMerkleTree {
static async fetchAndCacheDecimals( static async fetchAndCacheDecimals(
cache: Record<string, number>, cache: Record<string, number>,
provider: ethers.providers.Provider, provider: providers.Provider,
currencyAddress?: string, currencyAddress?: string,
): Promise<number> { ): Promise<number> {
if (!currencyAddress) { if (!currencyAddress) {
@@ -135,7 +135,7 @@ export class ShardedMerkleTree {
static async buildAndUpload( static async buildAndUpload(
snapshotInput: SnapshotInput, snapshotInput: SnapshotInput,
tokenDecimals: number, tokenDecimals: number,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
snapshotFormatVersion: SnapshotFormatVersion, snapshotFormatVersion: SnapshotFormatVersion,
shardNybbles = SHARD_NYBBLES, shardNybbles = SHARD_NYBBLES,
@@ -226,7 +226,7 @@ export class ShardedMerkleTree {
public async getProof( public async getProof(
address: string, address: string,
provider: ethers.providers.Provider, provider: providers.Provider,
snapshotFormatVersion: SnapshotFormatVersion, snapshotFormatVersion: SnapshotFormatVersion,
): Promise<SnapshotEntryWithProof | null> { ): Promise<SnapshotEntryWithProof | null> {
const shardId = address.slice(2, 2 + this.shardNybbles).toLowerCase(); const shardId = address.slice(2, 2 + this.shardNybbles).toLowerCase();
@@ -95,7 +95,7 @@ export const CONTRACT_ADDRESSES: Record<
openzeppelinForwarderEOA: "0x4f247c69184ad61036EC2Bb3213b69F10FbEDe1F", openzeppelinForwarderEOA: "0x4f247c69184ad61036EC2Bb3213b69F10FbEDe1F",
biconomyForwarder: "0xfe0fa3C06d03bDC7fb49c892BbB39113B534fB57", biconomyForwarder: "0xfe0fa3C06d03bDC7fb49c892BbB39113B534fB57",
twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0", twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0",
twRegistry: "0x7c487845f98938Bb955B1D5AD069d9a30e4131fd", twRegistry: TWRegistry_address,
twBYOCRegistry: AddressZero, twBYOCRegistry: AddressZero,
}, },
@@ -104,7 +104,7 @@ export const CONTRACT_ADDRESSES: Record<
openzeppelinForwarderEOA: "0x119704314Ef304EaAAE4b3c7C9ABd59272A28310", openzeppelinForwarderEOA: "0x119704314Ef304EaAAE4b3c7C9ABd59272A28310",
biconomyForwarder: AddressZero, biconomyForwarder: AddressZero,
twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0", twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0",
twRegistry: "0x7c487845f98938Bb955B1D5AD069d9a30e4131fd", twRegistry: TWRegistry_address,
twBYOCRegistry: AddressZero, twBYOCRegistry: AddressZero,
}, },
[ChainId.Optimism]: { [ChainId.Optimism]: {
@@ -112,7 +112,7 @@ export const CONTRACT_ADDRESSES: Record<
openzeppelinForwarderEOA: "0x7e80648EB2071E26937F9D42A513ccf4815fc702", openzeppelinForwarderEOA: "0x7e80648EB2071E26937F9D42A513ccf4815fc702",
biconomyForwarder: "0xefba8a2a82ec1fb1273806174f5e28fbb917cf95", biconomyForwarder: "0xefba8a2a82ec1fb1273806174f5e28fbb917cf95",
twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0", twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0",
twRegistry: "0x7c487845f98938Bb955B1D5AD069d9a30e4131fd", twRegistry: TWRegistry_address,
twBYOCRegistry: AddressZero, twBYOCRegistry: AddressZero,
}, },
@@ -121,7 +121,7 @@ export const CONTRACT_ADDRESSES: Record<
openzeppelinForwarderEOA: "0x119704314Ef304EaAAE4b3c7C9ABd59272A28310", openzeppelinForwarderEOA: "0x119704314Ef304EaAAE4b3c7C9ABd59272A28310",
biconomyForwarder: AddressZero, biconomyForwarder: AddressZero,
twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0", twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0",
twRegistry: "0x7c487845f98938Bb955B1D5AD069d9a30e4131fd", twRegistry: TWRegistry_address,
twBYOCRegistry: AddressZero, twBYOCRegistry: AddressZero,
}, },
[ChainId.BinanceSmartChainMainnet]: { [ChainId.BinanceSmartChainMainnet]: {
@@ -130,7 +130,7 @@ export const CONTRACT_ADDRESSES: Record<
biconomyForwarder: "0x86C80a8aa58e0A4fa09A69624c31Ab2a6CAD56b8", biconomyForwarder: "0x86C80a8aa58e0A4fa09A69624c31Ab2a6CAD56b8",
twBYOCRegistry: AddressZero, twBYOCRegistry: AddressZero,
twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0", twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0",
twRegistry: "0x7c487845f98938Bb955B1D5AD069d9a30e4131fd", twRegistry: TWRegistry_address,
}, },
[ChainId.BinanceSmartChainTestnet]: { [ChainId.BinanceSmartChainTestnet]: {
openzeppelinForwarder: "0x44bE9D54B9C8b5e57a3325E8Ec9154640e7c6955", openzeppelinForwarder: "0x44bE9D54B9C8b5e57a3325E8Ec9154640e7c6955",
@@ -138,7 +138,7 @@ export const CONTRACT_ADDRESSES: Record<
biconomyForwarder: "0x61456BF1715C1415730076BB79ae118E806E74d2", biconomyForwarder: "0x61456BF1715C1415730076BB79ae118E806E74d2",
twBYOCRegistry: AddressZero, twBYOCRegistry: AddressZero,
twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0", twFactory: "0xd24b3de085CFd8c54b94feAD08a7962D343E6DE0",
twRegistry: "0x7c487845f98938Bb955B1D5AD069d9a30e4131fd", twRegistry: TWRegistry_address,
}, },
[ChainId.Hardhat]: { [ChainId.Hardhat]: {
openzeppelinForwarder: AddressZero, openzeppelinForwarder: AddressZero,
+3 -3
View File
@@ -1,7 +1,7 @@
import type { NativeToken } from "../types/currency"; import type { NativeToken } from "../types/currency";
import { ChainId } from "./chains/ChainId"; import { ChainId } from "./chains/ChainId";
import { getSupportedChains } from "./chains/supportedChains"; import { getSupportedChains } from "./chains/supportedChains";
import { ethers } from "ethers"; import { constants } from "ethers";
/** /**
* @public * @public
@@ -221,7 +221,7 @@ export function getNativeTokenByChainId(chainId: ChainId): NativeToken {
symbol: chain.nativeCurrency.symbol, symbol: chain.nativeCurrency.symbol,
decimals: 18, decimals: 18,
wrapped: { wrapped: {
address: ethers.constants.AddressZero, address: constants.AddressZero,
name: `Wrapped ${chain.nativeCurrency.name}`, name: `Wrapped ${chain.nativeCurrency.name}`,
symbol: `W${chain.nativeCurrency.symbol}`, symbol: `W${chain.nativeCurrency.symbol}`,
}, },
@@ -233,7 +233,7 @@ export function getNativeTokenByChainId(chainId: ChainId): NativeToken {
symbol: "ETH", symbol: "ETH",
decimals: 18, decimals: 18,
wrapped: { wrapped: {
address: ethers.constants.AddressZero, address: constants.AddressZero,
name: "Wrapped Ether", name: "Wrapped Ether",
symbol: "WETH", symbol: "WETH",
}, },
@@ -14,7 +14,7 @@ import MulticallAbi from "@thirdweb-dev/contracts-js/dist/abis/IMulticall.json";
import SignatureMintERC721Abi from "@thirdweb-dev/contracts-js/dist/abis/ISignatureMintERC721.json"; import SignatureMintERC721Abi from "@thirdweb-dev/contracts-js/dist/abis/ISignatureMintERC721.json";
import SignatureMintERC721_V1Abi from "@thirdweb-dev/contracts-js/dist/abis/ISignatureMintERC721_V1.json"; import SignatureMintERC721_V1Abi from "@thirdweb-dev/contracts-js/dist/abis/ISignatureMintERC721_V1.json";
import TieredDropAbi from "@thirdweb-dev/contracts-js/dist/abis/LazyMintWithTier.json"; import TieredDropAbi from "@thirdweb-dev/contracts-js/dist/abis/LazyMintWithTier.json";
import SharedMetadataAbi from "@thirdweb-dev/contracts-js/dist/abis/ISharedMetadata.json"; import SharedMetadataAbi from "@thirdweb-dev/contracts-js/dist/abis/SharedMetadata.json";
import zora_IDropERC721 from "@thirdweb-dev/contracts-js/dist/abis/zora_IERC721Drop.json"; import zora_IDropERC721 from "@thirdweb-dev/contracts-js/dist/abis/zora_IERC721Drop.json";
export const FEATURE_NFT_BURNABLE = { export const FEATURE_NFT_BURNABLE = {
@@ -205,7 +205,7 @@ export const FEATURE_NFT_SHARED_METADATA = /* @__PURE__ */ {
namespace: "nft.sharedmetadata", namespace: "nft.sharedmetadata",
docLinks: { docLinks: {
sdk: "sdk.sharedmetadata", sdk: "sdk.sharedmetadata",
contracts: "ISharedMetadata", contracts: "SharedMetadata",
}, },
abis: [Erc721Abi, SharedMetadataAbi], abis: [Erc721Abi, SharedMetadataAbi],
features: {}, features: {},
@@ -128,7 +128,7 @@ export const FEATURE_PRIMARY_SALE = {
export const FEATURE_PLATFORM_FEE = { export const FEATURE_PLATFORM_FEE = {
name: "PlatformFee", name: "PlatformFee",
namespace: "platformFee", namespace: "platformFees",
docLinks: { docLinks: {
sdk: "sdk.platformfee", sdk: "sdk.platformfee",
contracts: "platformfee", contracts: "platformfee",
@@ -0,0 +1,11 @@
export const ADMIN_ROLE = ['admin'] as const;
export const NFT_BASE_CONTRACT_ROLES = ["admin", "minter", "transfer"] as const;
export const MARKETPLACE_CONTRACT_ROLES = ["admin", "lister", "asset"] as const;
export const PACK_CONTRACT_ROLES = ["admin", "minter", "asset", "transfer"] as const;
export const TOKEN_DROP_CONTRACT_ROLES = ["admin", "transfer"] as const;
export const MULTIWRAP_CONTRACT_ROLES = ["admin", "transfer", "minter", "unwrap", "asset"] as const
+35 -30
View File
@@ -19,10 +19,18 @@ import { Abi, AbiSchema } from "../schema/contracts/custom";
import { DropErc20ContractSchema } from "../schema/contracts/drop-erc20"; import { DropErc20ContractSchema } from "../schema/contracts/drop-erc20";
import { MultiwrapContractSchema } from "../schema/contracts/multiwrap"; import { MultiwrapContractSchema } from "../schema/contracts/multiwrap";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { ethers } from "ethers"; import type { providers } from "ethers";
import type { SmartContract as SmartContractType } from "./smart-contract"; import type { SmartContract as SmartContractType } from "./smart-contract";
import { getCompositeABIfromRelease } from "../common/plugin/getCompositeABIfromRelease"; import { getCompositeABIfromRelease } from "../common/plugin/getCompositeABIfromRelease";
import { getCompositePluginABI } from "../common/plugin/getCompositePluginABI"; import { getCompositePluginABI } from "../common/plugin/getCompositePluginABI";
import {
ADMIN_ROLE,
MARKETPLACE_CONTRACT_ROLES,
MULTIWRAP_CONTRACT_ROLES,
NFT_BASE_CONTRACT_ROLES,
PACK_CONTRACT_ROLES,
TOKEN_DROP_CONTRACT_ROLES,
} from "./contractRoles";
const prebuiltContractTypes = { const prebuiltContractTypes = {
vote: "vote", vote: "vote",
@@ -53,7 +61,7 @@ export const EditionDropInitializer = {
name: "DropERC1155" as const, name: "DropERC1155" as const,
contractType: prebuiltContractTypes["edition-drop"], contractType: prebuiltContractTypes["edition-drop"],
schema: DropErc1155ContractSchema, schema: DropErc1155ContractSchema,
roles: ["admin", "minter", "transfer"] as const, roles: NFT_BASE_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
) => { ) => {
@@ -75,7 +83,7 @@ export const EditionDropInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -99,7 +107,7 @@ export const EditionInitializer = {
name: "TokenERC1155" as const, name: "TokenERC1155" as const,
contractType: prebuiltContractTypes["edition"], contractType: prebuiltContractTypes["edition"],
schema: TokenErc1155ContractSchema, schema: TokenErc1155ContractSchema,
roles: ["admin", "minter", "transfer"] as const, roles: NFT_BASE_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
) => { ) => {
@@ -121,7 +129,7 @@ export const EditionInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -139,7 +147,7 @@ export const MarketplaceInitializer = {
name: "Marketplace" as const, name: "Marketplace" as const,
contractType: prebuiltContractTypes.marketplace, contractType: prebuiltContractTypes.marketplace,
schema: MarketplaceContractSchema, schema: MarketplaceContractSchema,
roles: ["admin", "lister", "asset"] as const, roles: MARKETPLACE_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
) => { ) => {
@@ -161,7 +169,7 @@ export const MarketplaceInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -180,7 +188,7 @@ export const MarketplaceV3Initializer = {
name: "MarketplaceV3" as const, name: "MarketplaceV3" as const,
contractType: prebuiltContractTypes["marketplace-v3"], contractType: prebuiltContractTypes["marketplace-v3"],
schema: MarketplaceContractSchema, schema: MarketplaceContractSchema,
roles: ["admin", "lister", "asset"] as const, roles: MARKETPLACE_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
) => { ) => {
@@ -202,7 +210,7 @@ export const MarketplaceV3Initializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const chainId = (await provider.getNetwork()).chainId; const chainId = (await provider.getNetwork()).chainId;
@@ -240,7 +248,7 @@ export const MultiwrapInitializer = {
name: "Multiwrap" as const, name: "Multiwrap" as const,
contractType: prebuiltContractTypes.multiwrap, contractType: prebuiltContractTypes.multiwrap,
schema: MultiwrapContractSchema, schema: MultiwrapContractSchema,
roles: ["admin", "transfer", "minter", "unwrap", "asset"] as const, roles: MULTIWRAP_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
) => { ) => {
@@ -262,7 +270,7 @@ export const MultiwrapInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -279,7 +287,7 @@ export const NFTCollectionInitializer = {
name: "TokenERC721" as const, name: "TokenERC721" as const,
contractType: prebuiltContractTypes["nft-collection"], contractType: prebuiltContractTypes["nft-collection"],
schema: TokenErc721ContractSchema, schema: TokenErc721ContractSchema,
roles: ["admin", "minter", "transfer"] as const, roles: NFT_BASE_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
@@ -302,7 +310,7 @@ export const NFTCollectionInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -320,7 +328,7 @@ export const NFTDropInitializer = {
name: "DropERC721" as const, name: "DropERC721" as const,
contractType: prebuiltContractTypes["nft-drop"], contractType: prebuiltContractTypes["nft-drop"],
schema: DropErc721ContractSchema, schema: DropErc721ContractSchema,
roles: ["admin", "minter", "transfer"] as const, roles: NFT_BASE_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
) => { ) => {
@@ -342,7 +350,7 @@ export const NFTDropInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -366,7 +374,7 @@ export const PackInitializer = {
name: "Pack" as const, name: "Pack" as const,
contractType: prebuiltContractTypes["pack"], contractType: prebuiltContractTypes["pack"],
schema: PackContractSchema, schema: PackContractSchema,
roles: ["admin", "minter", "asset", "transfer"] as const, roles: PACK_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
@@ -389,7 +397,7 @@ export const PackInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
): Promise<Abi> => { ): Promise<Abi> => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -408,7 +416,7 @@ export const SignatureDropInitializer = {
name: "SignatureDrop" as const, name: "SignatureDrop" as const,
contractType: prebuiltContractTypes["signature-drop"], contractType: prebuiltContractTypes["signature-drop"],
schema: DropErc721ContractSchema, schema: DropErc721ContractSchema,
roles: ["admin", "minter", "transfer"] as const, roles: NFT_BASE_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
@@ -431,7 +439,7 @@ export const SignatureDropInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -458,7 +466,7 @@ export const SplitInitializer = {
name: "Split" as const, name: "Split" as const,
contractType: prebuiltContractTypes["split"], contractType: prebuiltContractTypes["split"],
schema: SplitsContractSchema, schema: SplitsContractSchema,
roles: ["admin"] as const, roles: ADMIN_ROLE,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
@@ -481,7 +489,7 @@ export const SplitInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -498,7 +506,7 @@ export const TokenDropInitializer = {
name: "DropERC20" as const, name: "DropERC20" as const,
contractType: prebuiltContractTypes["token-drop"], contractType: prebuiltContractTypes["token-drop"],
schema: DropErc20ContractSchema, schema: DropErc20ContractSchema,
roles: ["admin", "transfer"] as const, roles: TOKEN_DROP_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
@@ -521,7 +529,7 @@ export const TokenDropInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -542,7 +550,7 @@ export const TokenInitializer = {
name: "TokenERC20" as const, name: "TokenERC20" as const,
contractType: prebuiltContractTypes.token, contractType: prebuiltContractTypes.token,
schema: TokenErc20ContractSchema, schema: TokenErc20ContractSchema,
roles: ["admin", "minter", "transfer"] as const, roles: NFT_BASE_CONTRACT_ROLES,
initialize: async ( initialize: async (
...[network, address, storage, options]: InitalizeParams ...[network, address, storage, options]: InitalizeParams
) => { ) => {
@@ -564,7 +572,7 @@ export const TokenInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -605,7 +613,7 @@ export const VoteInitializer = {
}, },
getAbi: async ( getAbi: async (
address: Address, address: Address,
provider: ethers.providers.Provider, provider: providers.Provider,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) => { ) => {
const abi = await fetchAbiFromAddress(address, provider, storage); const abi = await fetchAbiFromAddress(address, provider, storage);
@@ -618,10 +626,7 @@ export const VoteInitializer = {
}, },
}; };
async function getContractInfo( async function getContractInfo(address: Address, provider: providers.Provider) {
address: Address,
provider: ethers.providers.Provider,
) {
try { try {
return await getPrebuiltInfo(address, provider); return await getPrebuiltInfo(address, provider);
} catch (e) { } catch (e) {
@@ -28,6 +28,7 @@ import { SDKOptions } from "../../schema/sdk-options";
import { PrebuiltEditionDrop } from "../../types/eips"; import { PrebuiltEditionDrop } from "../../types/eips";
import { ThirdwebStorage, UploadProgressEvent } from "@thirdweb-dev/storage"; import { ThirdwebStorage, UploadProgressEvent } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers"; import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
import { NFT_BASE_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Setup a collection of NFTs with a customizable number of each NFT that are minted as users claim them. * Setup a collection of NFTs with a customizable number of each NFT that are minted as users claim them.
@@ -44,7 +45,7 @@ import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
* @public * @public
*/ */
export class EditionDrop extends StandardErc1155<PrebuiltEditionDrop> { export class EditionDrop extends StandardErc1155<PrebuiltEditionDrop> {
private static contractRoles = ["admin", "minter", "transfer"] as const; private static contractRoles = NFT_BASE_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
public sales: ContractPrimarySale<PrebuiltEditionDrop>; public sales: ContractPrimarySale<PrebuiltEditionDrop>;
@@ -27,6 +27,7 @@ import { EditionMetadataOrUri } from "../../schema/tokens/edition";
import type { TokenERC1155 } from "@thirdweb-dev/contracts-js"; import type { TokenERC1155 } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers"; import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
import { NFT_BASE_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Create a collection of NFTs that lets you mint multiple copies of each NFT. * Create a collection of NFTs that lets you mint multiple copies of each NFT.
@@ -43,7 +44,7 @@ import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
* @public * @public
*/ */
export class Edition extends StandardErc1155<TokenERC1155> { export class Edition extends StandardErc1155<TokenERC1155> {
static contractRoles = ["admin", "minter", "transfer"] as const; static contractRoles = NFT_BASE_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
public metadata: ContractMetadata< public metadata: ContractMetadata<
@@ -34,6 +34,7 @@ import { NewOfferEventObject } from "@thirdweb-dev/contracts-js/dist/declaration
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers"; import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
import { MARKETPLACE_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Create your own whitelabel marketplace that enables users to buy and sell any digital assets. * Create your own whitelabel marketplace that enables users to buy and sell any digital assets.
@@ -50,7 +51,7 @@ import invariant from "tiny-invariant";
* @public * @public
*/ */
export class Marketplace implements UpdateableNetwork { export class Marketplace implements UpdateableNetwork {
static contractRoles = ["admin", "lister", "asset"] as const; static contractRoles = MARKETPLACE_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
private contractWrapper: ContractWrapper<MarketplaceContract>; private contractWrapper: ContractWrapper<MarketplaceContract>;
@@ -32,6 +32,7 @@ import type {
} from "@thirdweb-dev/contracts-js"; } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { CallOverrides } from "ethers"; import { CallOverrides } from "ethers";
import { MARKETPLACE_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Create your own whitelabel marketplace that enables users to buy and sell any digital assets. * Create your own whitelabel marketplace that enables users to buy and sell any digital assets.
@@ -48,7 +49,7 @@ import { CallOverrides } from "ethers";
* @public * @public
*/ */
export class MarketplaceV3 implements UpdateableNetwork { export class MarketplaceV3 implements UpdateableNetwork {
static contractRoles = ["admin", "lister", "asset"] as const; static contractRoles = MARKETPLACE_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
private contractWrapper: ContractWrapper<MarketplaceV3Contract>; private contractWrapper: ContractWrapper<MarketplaceV3Contract>;
@@ -32,10 +32,11 @@ import {
TokensWrappedEvent, TokensWrappedEvent,
} from "@thirdweb-dev/contracts-js/dist/declarations/src/Multiwrap"; } from "@thirdweb-dev/contracts-js/dist/declarations/src/Multiwrap";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumberish, CallOverrides, ethers } from "ethers"; import { type BigNumberish, type CallOverrides, utils } from "ethers";
import { fetchCurrencyMetadata } from "../../common/currency/fetchCurrencyMetadata"; import { fetchCurrencyMetadata } from "../../common/currency/fetchCurrencyMetadata";
import { hasERC20Allowance } from "../../common/currency/hasERC20Allowance"; import { hasERC20Allowance } from "../../common/currency/hasERC20Allowance";
import { normalizePriceValue } from "../../common/currency/normalizePriceValue"; import { normalizePriceValue } from "../../common/currency/normalizePriceValue";
import { MULTIWRAP_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Multiwrap lets you wrap any number of ERC20, ERC721 and ERC1155 tokens you own into a single wrapped token bundle. * Multiwrap lets you wrap any number of ERC20, ERC721 and ERC1155 tokens you own into a single wrapped token bundle.
@@ -52,13 +53,7 @@ import { normalizePriceValue } from "../../common/currency/normalizePriceValue";
* @beta * @beta
*/ */
export class Multiwrap extends StandardErc721<MultiwrapContract> { export class Multiwrap extends StandardErc721<MultiwrapContract> {
static contractRoles = [ static contractRoles = MULTIWRAP_CONTRACT_ROLES;
"admin",
"transfer",
"minter",
"unwrap",
"asset",
] as const;
public abi: Abi; public abi: Abi;
public encoder: ContractEncoder<MultiwrapContract>; public encoder: ContractEncoder<MultiwrapContract>;
@@ -171,7 +166,7 @@ export class Multiwrap extends StandardErc721<MultiwrapContract> {
); );
erc20Tokens.push({ erc20Tokens.push({
contractAddress: token.assetContract, contractAddress: token.assetContract,
quantity: ethers.utils.formatUnits( quantity: utils.formatUnits(
token.totalAmount, token.totalAmount,
tokenMetadata.decimals, tokenMetadata.decimals,
), ),
@@ -25,6 +25,7 @@ import { SDKOptions } from "../../schema/sdk-options";
import type { TokenERC721 } from "@thirdweb-dev/contracts-js"; import type { TokenERC721 } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumberish, CallOverrides, constants } from "ethers"; import { BigNumberish, CallOverrides, constants } from "ethers";
import { NFT_BASE_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Create a collection of one-of-one NFTs. * Create a collection of one-of-one NFTs.
@@ -41,7 +42,7 @@ import { BigNumberish, CallOverrides, constants } from "ethers";
* @public * @public
*/ */
export class NFTCollection extends StandardErc721<TokenERC721> { export class NFTCollection extends StandardErc721<TokenERC721> {
static contractRoles = ["admin", "minter", "transfer"] as const; static contractRoles = NFT_BASE_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
public metadata: ContractMetadata< public metadata: ContractMetadata<
@@ -33,6 +33,7 @@ import { PrebuiltNFTDrop } from "../../types/eips";
import { UploadProgressEvent } from "../../types/events"; import { UploadProgressEvent } from "../../types/events";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers"; import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
import { NFT_BASE_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Setup a collection of one-of-one NFTs that are minted as users claim them. * Setup a collection of one-of-one NFTs that are minted as users claim them.
@@ -49,7 +50,7 @@ import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
* @public * @public
*/ */
export class NFTDrop extends StandardErc721<PrebuiltNFTDrop> { export class NFTDrop extends StandardErc721<PrebuiltNFTDrop> {
static contractRoles = ["admin", "minter", "transfer"] as const; static contractRoles = NFT_BASE_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
public encoder: ContractEncoder<PrebuiltNFTDrop>; public encoder: ContractEncoder<PrebuiltNFTDrop>;
@@ -45,10 +45,17 @@ import {
PackOpenedEvent, PackOpenedEvent,
} from "@thirdweb-dev/contracts-js/dist/declarations/src/Pack"; } from "@thirdweb-dev/contracts-js/dist/declarations/src/Pack";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, CallOverrides, ethers } from "ethers"; import {
BigNumber,
type BigNumberish,
type CallOverrides,
constants,
utils,
} from "ethers";
import { fetchCurrencyMetadata } from "../../common/currency/fetchCurrencyMetadata"; import { fetchCurrencyMetadata } from "../../common/currency/fetchCurrencyMetadata";
import { hasERC20Allowance } from "../../common/currency/hasERC20Allowance"; import { hasERC20Allowance } from "../../common/currency/hasERC20Allowance";
import { normalizePriceValue } from "../../common/currency/normalizePriceValue"; import { normalizePriceValue } from "../../common/currency/normalizePriceValue";
import { PACK_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Create lootboxes of NFTs with rarity based open mechanics. * Create lootboxes of NFTs with rarity based open mechanics.
@@ -65,7 +72,7 @@ import { normalizePriceValue } from "../../common/currency/normalizePriceValue";
* @public * @public
*/ */
export class Pack extends StandardErc1155<PackContract> { export class Pack extends StandardErc1155<PackContract> {
static contractRoles = ["admin", "minter", "asset", "transfer"] as const; static contractRoles = PACK_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
public metadata: ContractMetadata<PackContract, typeof PackContractSchema>; public metadata: ContractMetadata<PackContract, typeof PackContractSchema>;
@@ -243,7 +250,7 @@ export class Pack extends StandardErc1155<PackContract> {
public async isTransferRestricted(): Promise<boolean> { public async isTransferRestricted(): Promise<boolean> {
const anyoneCanTransfer = await this.contractWrapper.readContract.hasRole( const anyoneCanTransfer = await this.contractWrapper.readContract.hasRole(
getRoleHash("transfer"), getRoleHash("transfer"),
ethers.constants.AddressZero, constants.AddressZero,
); );
return !anyoneCanTransfer; return !anyoneCanTransfer;
} }
@@ -283,11 +290,11 @@ export class Pack extends StandardErc1155<PackContract> {
this.contractWrapper.getProvider(), this.contractWrapper.getProvider(),
reward.assetContract, reward.assetContract,
); );
const quantityPerReward = ethers.utils.formatUnits( const quantityPerReward = utils.formatUnits(
amount, amount,
tokenMetadata.decimals, tokenMetadata.decimals,
); );
const totalRewards = ethers.utils.formatUnits( const totalRewards = utils.formatUnits(
BigNumber.from(reward.totalAmount).div(amount), BigNumber.from(reward.totalAmount).div(amount),
tokenMetadata.decimals, tokenMetadata.decimals,
); );
@@ -619,7 +626,7 @@ export class Pack extends StandardErc1155<PackContract> {
); );
erc20Rewards.push({ erc20Rewards.push({
contractAddress: reward.assetContract, contractAddress: reward.assetContract,
quantityPerReward: ethers.utils quantityPerReward: utils
.formatUnits(reward.totalAmount, tokenMetadata.decimals) .formatUnits(reward.totalAmount, tokenMetadata.decimals)
.toString(), .toString(),
}); });
@@ -35,6 +35,7 @@ import { UploadProgressEvent } from "../../types/events";
import type { SignatureDrop as SignatureDropContract } from "@thirdweb-dev/contracts-js"; import type { SignatureDrop as SignatureDropContract } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers"; import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
import { NFT_BASE_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Setup a collection of NFTs where when it comes to minting, you can authorize * Setup a collection of NFTs where when it comes to minting, you can authorize
@@ -53,7 +54,7 @@ import { BigNumber, BigNumberish, CallOverrides, constants } from "ethers";
* @public * @public
*/ */
export class SignatureDrop extends StandardErc721<SignatureDropContract> { export class SignatureDrop extends StandardErc721<SignatureDropContract> {
static contractRoles = ["admin", "minter", "transfer"] as const; static contractRoles = NFT_BASE_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
public owner: ContractOwner<SignatureDropContract>; public owner: ContractOwner<SignatureDropContract>;
@@ -26,6 +26,7 @@ import ERC20Abi from "@thirdweb-dev/contracts-js/dist/abis/IERC20.json";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, CallOverrides, Contract } from "ethers"; import { BigNumber, CallOverrides, Contract } from "ethers";
import { fetchCurrencyValue } from "../../common/currency/fetchCurrencyValue"; import { fetchCurrencyValue } from "../../common/currency/fetchCurrencyValue";
import { ADMIN_ROLE } from "../contractRoles";
/** /**
* Create custom royalty splits to distribute funds. * Create custom royalty splits to distribute funds.
@@ -42,7 +43,7 @@ import { fetchCurrencyValue } from "../../common/currency/fetchCurrencyValue";
* @public * @public
*/ */
export class Split implements UpdateableNetwork { export class Split implements UpdateableNetwork {
static contractRoles = ["admin"] as const; static contractRoles = ADMIN_ROLE;
private contractWrapper: ContractWrapper<SplitContract>; private contractWrapper: ContractWrapper<SplitContract>;
private storage: ThirdwebStorage; private storage: ThirdwebStorage;
@@ -24,6 +24,7 @@ import type { CurrencyValue, Amount } from "../../types/currency";
import { PrebuiltTokenDrop } from "../../types/eips"; import { PrebuiltTokenDrop } from "../../types/eips";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { CallOverrides, constants } from "ethers"; import { CallOverrides, constants } from "ethers";
import { TOKEN_DROP_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Create a Drop contract for a standard crypto token or cryptocurrency. * Create a Drop contract for a standard crypto token or cryptocurrency.
@@ -39,7 +40,7 @@ import { CallOverrides, constants } from "ethers";
* *
*/ */
export class TokenDrop extends StandardErc20<PrebuiltTokenDrop> { export class TokenDrop extends StandardErc20<PrebuiltTokenDrop> {
static contractRoles = ["admin", "transfer"] as const; static contractRoles = TOKEN_DROP_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
public metadata: ContractMetadata< public metadata: ContractMetadata<
@@ -26,6 +26,7 @@ import type { CurrencyValue, Amount } from "../../types/currency";
import type { TokenERC20 } from "@thirdweb-dev/contracts-js"; import type { TokenERC20 } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { CallOverrides, constants } from "ethers"; import { CallOverrides, constants } from "ethers";
import { NFT_BASE_CONTRACT_ROLES } from "../contractRoles";
/** /**
* Create a standard crypto token or cryptocurrency. * Create a standard crypto token or cryptocurrency.
@@ -42,7 +43,7 @@ import { CallOverrides, constants } from "ethers";
* @public * @public
*/ */
export class Token extends StandardErc20<TokenERC20> { export class Token extends StandardErc20<TokenERC20> {
static contractRoles = ["admin", "minter", "transfer"] as const; static contractRoles = NFT_BASE_CONTRACT_ROLES;
public abi: Abi; public abi: Abi;
public metadata: ContractMetadata< public metadata: ContractMetadata<
@@ -29,10 +29,10 @@ import { ProposalCreatedEvent } from "@thirdweb-dev/contracts-js/dist/declaratio
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { import {
BigNumber, BigNumber,
BigNumberish, type BigNumberish,
CallOverrides, type CallOverrides,
Contract, Contract,
ethers, utils,
} from "ethers"; } from "ethers";
import { fetchCurrencyMetadata } from "../../common/currency/fetchCurrencyMetadata"; import { fetchCurrencyMetadata } from "../../common/currency/fetchCurrencyMetadata";
import { fetchCurrencyValue } from "../../common/currency/fetchCurrencyValue"; import { fetchCurrencyValue } from "../../common/currency/fetchCurrencyValue";
@@ -253,7 +253,7 @@ export class Vote implements UpdateableNetwork {
const tos = proposal.executions.map((p) => p.toAddress); const tos = proposal.executions.map((p) => p.toAddress);
const values = proposal.executions.map((p) => p.nativeTokenValue); const values = proposal.executions.map((p) => p.nativeTokenValue);
const datas = proposal.executions.map((p) => p.transactionData); const datas = proposal.executions.map((p) => p.transactionData);
const descriptionHash = ethers.utils.id(proposal.description); const descriptionHash = utils.id(proposal.description);
try { try {
await this.contractWrapper await this.contractWrapper
.callStatic() .callStatic()
@@ -278,7 +278,7 @@ export class Vote implements UpdateableNetwork {
symbol: "", symbol: "",
decimals: 18, decimals: 18,
value: balance, value: balance,
displayValue: ethers.utils.formatUnits(balance, 18), displayValue: utils.formatUnits(balance, 18),
}; };
} }
@@ -475,7 +475,7 @@ export class Vote implements UpdateableNetwork {
const tos = proposal.executions.map((p) => p.toAddress); const tos = proposal.executions.map((p) => p.toAddress);
const values = proposal.executions.map((p) => p.nativeTokenValue); const values = proposal.executions.map((p) => p.nativeTokenValue);
const datas = proposal.executions.map((p) => p.transactionData); const datas = proposal.executions.map((p) => p.transactionData);
const descriptionHash = ethers.utils.id(proposal.description); const descriptionHash = utils.id(proposal.description);
return Transaction.fromContractWrapper({ return Transaction.fromContractWrapper({
contractWrapper: this.contractWrapper, contractWrapper: this.contractWrapper,
@@ -13,8 +13,8 @@ import { z } from "zod";
* @example * @example
* ```javascript * ```javascript
* const contract = await sdk.getContract("{{contract_address}}"); * const contract = await sdk.getContract("{{contract_address}}");
* const feeInfo = await contract.platformFee.get(); * const feeInfo = await contract.platformFees.get();
* await contract.platformFee.set({ * await contract.platformFees.set({
* platform_fee_basis_points: 100, // 1% fee * platform_fee_basis_points: 100, // 1% fee
* platform_fee_recipient: "0x..." // the fee recipient * platform_fee_recipient: "0x..." // the fee recipient
* }) * })
@@ -36,7 +36,7 @@ export class ContractPlatformFee<TContract extends IPlatformFee>
* *
* @example * @example
* ```javascript * ```javascript
* const feeInfo = await contract.platformFee.get(); * const feeInfo = await contract.platformFees.get();
* console.log(feeInfo.platform_fee_recipient); * console.log(feeInfo.platform_fee_recipient);
* console.log(feeInfo.platform_fee_basis_points); * console.log(feeInfo.platform_fee_basis_points);
* ``` * ```
@@ -56,7 +56,7 @@ export class ContractPlatformFee<TContract extends IPlatformFee>
* *
* @example * @example
* ```javascript * ```javascript
* await contract.platformFee.set({ * await contract.platformFees.set({
* platform_fee_basis_points: 100, // 1% fee * platform_fee_basis_points: 100, // 1% fee
* platform_fee_recipient: "0x..." // the fee recipient * platform_fee_recipient: "0x..." // the fee recipient
* }) * })
@@ -1,4 +1,4 @@
import { ethers } from "ethers"; import { utils } from "ethers";
import { import {
verifyThirdwebPrebuiltImplementation, verifyThirdwebPrebuiltImplementation,
checkVerificationStatus, checkVerificationStatus,
@@ -123,7 +123,7 @@ export class ContractVerifier extends RPCConnectionHandler {
return arg.value; return arg.value;
}); });
encodedArgs = ethers.utils.defaultAbiCoder.encode( encodedArgs = utils.defaultAbiCoder.encode(
paramTypes, paramTypes,
paramValues, paramValues,
); );
@@ -33,13 +33,16 @@ import fetch from "cross-fetch";
import { import {
BaseContract, BaseContract,
BigNumber, BigNumber,
BytesLike, type BytesLike,
CallOverrides, type CallOverrides,
Contract, Contract,
ContractInterface, type ContractInterface,
ContractTransaction, type ContractTransaction,
ethers, utils,
providers, type ContractFunction,
type providers,
type Signer,
constants,
} from "ethers"; } from "ethers";
import { ConnectionInfo } from "ethers/lib/utils.js"; import { ConnectionInfo } from "ethers/lib/utils.js";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
@@ -144,7 +147,7 @@ export class ContractWrapper<
const baseBlockFee = const baseBlockFee =
block && block.baseFeePerGas block && block.baseFeePerGas
? block.baseFeePerGas ? block.baseFeePerGas
: ethers.utils.parseUnits("1", "gwei"); : utils.parseUnits("1", "gwei");
let defaultPriorityFee: BigNumber; let defaultPriorityFee: BigNumber;
if (chainId === ChainId.Mumbai || chainId === ChainId.Polygon) { if (chainId === ChainId.Mumbai || chainId === ChainId.Polygon) {
// for polygon, get fee data from gas station // for polygon, get fee data from gas station
@@ -192,8 +195,8 @@ export class ContractWrapper<
break; break;
} }
let txGasPrice = defaultPriorityFeePerGas.add(extraTip); let txGasPrice = defaultPriorityFeePerGas.add(extraTip);
const max = ethers.utils.parseUnits(maxGasPrice.toString(), "gwei"); // no more than max gas setting const max = utils.parseUnits(maxGasPrice.toString(), "gwei"); // no more than max gas setting
const min = ethers.utils.parseUnits("2.5", "gwei"); // no less than 2.5 gwei const min = utils.parseUnits("2.5", "gwei"); // no less than 2.5 gwei
if (txGasPrice.gt(max)) { if (txGasPrice.gt(max)) {
txGasPrice = max; txGasPrice = max;
} }
@@ -224,7 +227,7 @@ export class ContractWrapper<
break; break;
} }
txGasPrice = txGasPrice.add(extraTip); txGasPrice = txGasPrice.add(extraTip);
const max = ethers.utils.parseUnits(maxGasPrice.toString(), "gwei"); const max = utils.parseUnits(maxGasPrice.toString(), "gwei");
if (txGasPrice.gt(max)) { if (txGasPrice.gt(max)) {
txGasPrice = max; txGasPrice = max;
} }
@@ -352,7 +355,7 @@ export class ContractWrapper<
if (fn === "multicall" && Array.isArray(args[0]) && args[0].length > 0) { if (fn === "multicall" && Array.isArray(args[0]) && args[0].length > 0) {
const from = await this.getSignerAddress(); const from = await this.getSignerAddress();
args[0] = args[0].map((tx: any) => args[0] = args[0].map((tx: any) =>
ethers.utils.solidityPack(["bytes", "address"], [tx, from]), utils.solidityPack(["bytes", "address"], [tx, from]),
); );
} }
@@ -414,9 +417,7 @@ export class ContractWrapper<
args: any[], args: any[],
callOverrides: CallOverrides, callOverrides: CallOverrides,
): Promise<ContractTransaction> { ): Promise<ContractTransaction> {
const func: ethers.ContractFunction = (this.writeContract.functions as any)[ const func: ContractFunction = (this.writeContract.functions as any)[fn];
fn
];
if (!func) { if (!func) {
throw new Error(`invalid function: "${fn.toString()}"`); throw new Error(`invalid function: "${fn.toString()}"`);
} }
@@ -469,7 +470,7 @@ export class ContractWrapper<
args: any[], args: any[],
callOverrides: CallOverrides, callOverrides: CallOverrides,
) { ) {
const provider = this.getProvider() as ethers.providers.Provider & { const provider = this.getProvider() as providers.Provider & {
connection?: ConnectionInfo; connection?: ConnectionInfo;
}; };
@@ -619,7 +620,7 @@ export class ContractWrapper<
} }
public async signTypedData( public async signTypedData(
signer: ethers.Signer, signer: Signer,
domain: { domain: {
name: string; name: string;
version: string; version: string;
@@ -679,7 +680,7 @@ export class ContractWrapper<
const provider = this.getProvider(); const provider = this.getProvider();
invariant(signer && provider, "signer and provider must be set"); invariant(signer && provider, "signer and provider must be set");
const forwarder = new ethers.Contract( const forwarder = new Contract(
getContractAddressByChainId( getContractAddressByChainId(
transaction.chainId, transaction.chainId,
"biconomyForwarder", "biconomyForwarder",
@@ -696,7 +697,7 @@ export class ContractWrapper<
const request = { const request = {
from: transaction.from, from: transaction.from,
to: transaction.to, to: transaction.to,
token: ethers.constants.AddressZero, token: constants.AddressZero,
txGas: transaction.gasLimit.toNumber(), txGas: transaction.gasLimit.toNumber(),
tokenGasPrice: "0", tokenGasPrice: "0",
batchId, batchId,
@@ -711,8 +712,8 @@ export class ContractWrapper<
data: transaction.data, data: transaction.data,
}; };
const hashToSign = ethers.utils.arrayify( const hashToSign = utils.arrayify(
ethers.utils.solidityKeccak256( utils.solidityKeccak256(
[ [
"address", "address",
"address", "address",
@@ -733,7 +734,7 @@ export class ContractWrapper<
request.batchId, request.batchId,
request.batchNonce, request.batchNonce,
request.deadline, request.deadline,
ethers.utils.keccak256(request.data), utils.keccak256(request.data),
], ],
), ),
); );
@@ -872,7 +873,7 @@ export class ContractWrapper<
amount, amount,
); );
const { r, s, v } = ethers.utils.splitSignature(sig); const { r, s, v } = utils.splitSignature(sig);
message = { message = {
to: this.readContract.address, to: this.readContract.address,
@@ -26,7 +26,7 @@ import type {
import DeprecatedAbi from "@thirdweb-dev/contracts-js/dist/abis/IDelayedRevealDeprecated.json"; import DeprecatedAbi from "@thirdweb-dev/contracts-js/dist/abis/IDelayedRevealDeprecated.json";
import { TokensLazyMintedEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/DropERC721"; import { TokensLazyMintedEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/DropERC721";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, ethers } from "ethers"; import { BigNumber, type BigNumberish, utils, Contract } from "ethers";
import type { TransactionResultWithId } from "../types"; import type { TransactionResultWithId } from "../types";
/** /**
@@ -135,7 +135,7 @@ export class DelayedReveal<
); );
const encryptedBaseUri = const encryptedBaseUri =
await this.contractWrapper.readContract.encryptDecrypt( await this.contractWrapper.readContract.encryptDecrypt(
ethers.utils.toUtf8Bytes(baseUri), utils.toUtf8Bytes(baseUri),
hashedPassword, hashedPassword,
); );
@@ -145,11 +145,11 @@ export class DelayedReveal<
data = encryptedBaseUri; data = encryptedBaseUri;
} else { } else {
const chainId = await this.contractWrapper.getChainID(); const chainId = await this.contractWrapper.getChainID();
const provenanceHash = ethers.utils.solidityKeccak256( const provenanceHash = utils.solidityKeccak256(
["bytes", "bytes", "uint256"], ["bytes", "bytes", "uint256"],
[ethers.utils.toUtf8Bytes(baseUri), hashedPassword, chainId], [utils.toUtf8Bytes(baseUri), hashedPassword, chainId],
); );
data = ethers.utils.defaultAbiCoder.encode( data = utils.defaultAbiCoder.encode(
["bytes", "bytes32"], ["bytes", "bytes32"],
[encryptedBaseUri, provenanceHash], [encryptedBaseUri, provenanceHash],
); );
@@ -286,14 +286,11 @@ export class DelayedReveal<
), ),
); );
const encryptedBaseUris = encryptedUriData.map((data) => { const encryptedBaseUris = encryptedUriData.map((data) => {
if (ethers.utils.hexDataLength(data) > 0) { if (utils.hexDataLength(data) > 0) {
if (legacyContract) { if (legacyContract) {
return data; return data;
} }
const result = ethers.utils.defaultAbiCoder.decode( const result = utils.defaultAbiCoder.decode(["bytes", "bytes32"], data);
["bytes", "bytes32"],
data,
);
return result[0]; return result[0];
} else { } else {
return data; return data;
@@ -306,9 +303,7 @@ export class DelayedReveal<
batchUri: meta.uri, batchUri: meta.uri,
placeholderMetadata: meta, placeholderMetadata: meta,
})) }))
.filter( .filter((_, index) => utils.hexDataLength(encryptedBaseUris[index]) > 0);
(_, index) => ethers.utils.hexDataLength(encryptedBaseUris[index]) > 0,
);
} }
/** /**
@@ -322,7 +317,7 @@ export class DelayedReveal<
) { ) {
const chainId = await this.contractWrapper.getChainID(); const chainId = await this.contractWrapper.getChainID();
const contractAddress = this.contractWrapper.readContract.address; const contractAddress = this.contractWrapper.readContract.address;
return ethers.utils.solidityKeccak256( return utils.solidityKeccak256(
["string", "uint256", "uint256", "address"], ["string", "uint256", "uint256", "address"],
[password, chainId, batchTokenIndex, contractAddress], [password, chainId, batchTokenIndex, contractAddress],
); );
@@ -353,7 +348,7 @@ export class DelayedReveal<
} }
private async getLegacyEncryptedData(index: BigNumber) { private async getLegacyEncryptedData(index: BigNumber) {
const legacy = new ethers.Contract( const legacy = new Contract(
this.contractWrapper.readContract.address, this.contractWrapper.readContract.address,
DeprecatedAbi, DeprecatedAbi,
this.contractWrapper.getProvider(), this.contractWrapper.getProvider(),
@@ -44,7 +44,7 @@ import type { IDropClaimCondition_V2 } from "@thirdweb-dev/contracts-js/dist/dec
import type { IDropSinglePhase } from "@thirdweb-dev/contracts-js/src/DropSinglePhase"; import type { IDropSinglePhase } from "@thirdweb-dev/contracts-js/src/DropSinglePhase";
import type { IClaimCondition } from "@thirdweb-dev/contracts-js/src/IDrop"; import type { IClaimCondition } from "@thirdweb-dev/contracts-js/src/IDrop";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, constants, ethers, utils } from "ethers"; import { BigNumber, type BigNumberish, constants, utils } from "ethers";
import deepEqual from "fast-deep-equal"; import deepEqual from "fast-deep-equal";
import { fetchSnapshotEntryForAddress } from "../../common/claim-conditions/fetchSnapshotEntryForAddress"; import { fetchSnapshotEntryForAddress } from "../../common/claim-conditions/fetchSnapshotEntryForAddress";
import { abstractContractModelToLegacy } from "../../common/claim-conditions/abstractContractModelToLegacy"; import { abstractContractModelToLegacy } from "../../common/claim-conditions/abstractContractModelToLegacy";
@@ -229,7 +229,7 @@ export class DropClaimConditions<
let claimCondition: ClaimCondition; let claimCondition: ClaimCondition;
const decimals = await this.getTokenDecimals(); const decimals = await this.getTokenDecimals();
const quantityWithDecimals = ethers.utils.parseUnits( const quantityWithDecimals = utils.parseUnits(
AmountSchema.parse(quantity), AmountSchema.parse(quantity),
decimals, decimals,
); );
@@ -265,7 +265,7 @@ export class DropClaimConditions<
} }
if (claimCondition.availableSupply !== "unlimited") { if (claimCondition.availableSupply !== "unlimited") {
const supplyWithDecimals = ethers.utils.parseUnits( const supplyWithDecimals = utils.parseUnits(
claimCondition.availableSupply, claimCondition.availableSupply,
decimals, decimals,
); );
@@ -276,9 +276,7 @@ export class DropClaimConditions<
} }
// check for merkle root inclusion // check for merkle root inclusion
const merkleRootArray = ethers.utils.stripZeros( const merkleRootArray = utils.stripZeros(claimCondition.merkleRootHash);
claimCondition.merkleRootHash,
);
const hasAllowList = merkleRootArray.length > 0; const hasAllowList = merkleRootArray.length > 0;
let allowListEntry: SnapshotEntryWithProof | null = null; let allowListEntry: SnapshotEntryWithProof | null = null;
if (hasAllowList) { if (hasAllowList) {
@@ -492,7 +490,7 @@ export class DropClaimConditions<
): Promise<SnapshotEntryWithProof | null> { ): Promise<SnapshotEntryWithProof | null> {
const claimCondition = await this.get(claimConditionId); const claimCondition = await this.get(claimConditionId);
const merkleRoot = claimCondition.merkleRoot; const merkleRoot = claimCondition.merkleRoot;
const merkleRootArray = ethers.utils.stripZeros(merkleRoot); const merkleRootArray = utils.stripZeros(merkleRoot);
if (merkleRootArray.length > 0) { if (merkleRootArray.length > 0) {
const metadata = await this.metadata.get(); const metadata = await this.metadata.get();
const resolvedAddress = await resolveAddress(claimerAddress); const resolvedAddress = await resolveAddress(claimerAddress);
@@ -563,7 +561,7 @@ export class DropClaimConditions<
claimConditionsProcessed = [ claimConditionsProcessed = [
{ {
startTime: new Date(0), startTime: new Date(0),
currencyAddress: ethers.constants.AddressZero, currencyAddress: constants.AddressZero,
price: 0, price: 0,
maxClaimableSupply: 0, maxClaimableSupply: 0,
maxClaimablePerWallet: 0, maxClaimablePerWallet: 0,
@@ -796,7 +794,7 @@ export class DropClaimConditions<
proof: claimVerification.proofs, proof: claimVerification.proofs,
maxQuantityInAllowlist: claimVerification.maxClaimable, maxQuantityInAllowlist: claimVerification.maxClaimable,
} as IDropSinglePhase_V1.AllowlistProofStruct, } as IDropSinglePhase_V1.AllowlistProofStruct,
ethers.utils.toUtf8Bytes(""), utils.toUtf8Bytes(""),
]; ];
} }
return [ return [
@@ -810,7 +808,7 @@ export class DropClaimConditions<
pricePerToken: claimVerification.priceInProof, pricePerToken: claimVerification.priceInProof,
currency: claimVerification.currencyAddressInProof, currency: claimVerification.currencyAddressInProof,
} as IDropSinglePhase.AllowlistProofStruct, } as IDropSinglePhase.AllowlistProofStruct,
ethers.utils.toUtf8Bytes(""), utils.toUtf8Bytes(""),
]; ];
} }
@@ -39,7 +39,7 @@ import IERC20ABI from "@thirdweb-dev/contracts-js/dist/abis/IERC20.json";
import type { IDropClaimCondition_V2 } from "@thirdweb-dev/contracts-js/dist/declarations/src/DropERC20_V2"; import type { IDropClaimCondition_V2 } from "@thirdweb-dev/contracts-js/dist/declarations/src/DropERC20_V2";
import type { IClaimCondition } from "@thirdweb-dev/contracts-js/src/IDrop"; import type { IClaimCondition } from "@thirdweb-dev/contracts-js/src/IDrop";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, constants, ethers, utils } from "ethers"; import { BigNumber, type BigNumberish, constants, utils } from "ethers";
import deepEqual from "fast-deep-equal"; import deepEqual from "fast-deep-equal";
import { legacyContractModelToAbstract } from "../../common/claim-conditions/legacyContractModelToAbstract"; import { legacyContractModelToAbstract } from "../../common/claim-conditions/legacyContractModelToAbstract";
import { newContractModelToAbstract } from "../../common/claim-conditions/newContractModelToAbstract"; import { newContractModelToAbstract } from "../../common/claim-conditions/newContractModelToAbstract";
@@ -273,9 +273,7 @@ export class DropErc1155ClaimConditions<
} }
// check for merkle root inclusion // check for merkle root inclusion
const merkleRootArray = ethers.utils.stripZeros( const merkleRootArray = utils.stripZeros(claimCondition.merkleRootHash);
claimCondition.merkleRootHash,
);
const hasAllowList = merkleRootArray.length > 0; const hasAllowList = merkleRootArray.length > 0;
let allowListEntry: SnapshotEntryWithProof | null = null; let allowListEntry: SnapshotEntryWithProof | null = null;
if (hasAllowList) { if (hasAllowList) {
@@ -467,7 +465,7 @@ export class DropErc1155ClaimConditions<
): Promise<SnapshotEntryWithProof | null> { ): Promise<SnapshotEntryWithProof | null> {
const claimCondition = await this.get(tokenId, claimConditionId); const claimCondition = await this.get(tokenId, claimConditionId);
const merkleRoot = claimCondition.merkleRoot; const merkleRoot = claimCondition.merkleRoot;
const merkleRootArray = ethers.utils.stripZeros(merkleRoot); const merkleRootArray = utils.stripZeros(merkleRoot);
if (merkleRootArray.length > 0) { if (merkleRootArray.length > 0) {
const metadata = await this.metadata.get(); const metadata = await this.metadata.get();
const resolvedAddress = await resolveAddress(claimerAddress); const resolvedAddress = await resolveAddress(claimerAddress);
@@ -591,7 +589,7 @@ export class DropErc1155ClaimConditions<
claimConditionsProcessed = [ claimConditionsProcessed = [
{ {
startTime: new Date(0), startTime: new Date(0),
currencyAddress: ethers.constants.AddressZero, currencyAddress: constants.AddressZero,
price: 0, price: 0,
maxClaimableSupply: 0, maxClaimableSupply: 0,
maxClaimablePerWallet: 0, maxClaimablePerWallet: 0,
@@ -840,7 +838,7 @@ export class DropErc1155ClaimConditions<
proof: claimVerification.proofs, proof: claimVerification.proofs,
maxQuantityInAllowlist: claimVerification.maxClaimable, maxQuantityInAllowlist: claimVerification.maxClaimable,
} as IDropSinglePhase_V1.AllowlistProofStruct, } as IDropSinglePhase_V1.AllowlistProofStruct,
ethers.utils.toUtf8Bytes(""), utils.toUtf8Bytes(""),
]; ];
} }
return [ return [
@@ -855,7 +853,7 @@ export class DropErc1155ClaimConditions<
pricePerToken: claimVerification.priceInProof, pricePerToken: claimVerification.priceInProof,
currency: claimVerification.currencyAddressInProof, currency: claimVerification.currencyAddressInProof,
} as IDropSinglePhase.AllowlistProofStruct, } as IDropSinglePhase.AllowlistProofStruct,
ethers.utils.toUtf8Bytes(""), utils.toUtf8Bytes(""),
]; ];
} }
@@ -10,7 +10,7 @@ import { ContractWrapper } from "./contract-wrapper";
import { Transaction } from "./transactions"; import { Transaction } from "./transactions";
import type { IMintableERC1155 } from "@thirdweb-dev/contracts-js"; import type { IMintableERC1155 } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { ethers } from "ethers"; import { constants } from "ethers";
import { uploadOrExtractURIs } from "../../common/nft"; import { uploadOrExtractURIs } from "../../common/nft";
import type { IMulticall } from "@thirdweb-dev/contracts-js"; import type { IMulticall } from "@thirdweb-dev/contracts-js";
import { TokensMintedEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/TokenERC1155"; import { TokensMintedEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/TokenERC1155";
@@ -91,7 +91,7 @@ export class Erc1155BatchMintable implements DetectableFeature {
"mintTo", "mintTo",
[ [
resolvedAddress, resolvedAddress,
ethers.constants.MaxUint256, constants.MaxUint256,
uri, uri,
supplies[index], supplies[index],
], ],
@@ -12,7 +12,7 @@ import { TransactionResultWithId } from "../types";
import { ContractWrapper } from "./contract-wrapper"; import { ContractWrapper } from "./contract-wrapper";
import { Transaction } from "./transactions"; import { Transaction } from "./transactions";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { ethers } from "ethers"; import { type providers, utils } from "ethers";
import { getPrebuiltInfo } from "../../common/legacy"; import { getPrebuiltInfo } from "../../common/legacy";
import { uploadOrExtractURIs } from "../../common/nft"; import { uploadOrExtractURIs } from "../../common/nft";
import { BaseDelayedRevealERC1155 } from "../../types/eips"; import { BaseDelayedRevealERC1155 } from "../../types/eips";
@@ -124,7 +124,7 @@ export class Erc1155LazyMintable implements DetectableFeature {
} }
} }
const parse = (receipt: ethers.providers.TransactionReceipt) => { const parse = (receipt: providers.TransactionReceipt) => {
const event = this.contractWrapper.parseLogs<TokensLazyMintedEvent>( const event = this.contractWrapper.parseLogs<TokensLazyMintedEvent>(
"TokensLazyMinted", "TokensLazyMinted",
receipt?.logs, receipt?.logs,
@@ -166,7 +166,7 @@ export class Erc1155LazyMintable implements DetectableFeature {
args: [ args: [
batch.length, batch.length,
`${baseUri.endsWith("/") ? baseUri : `${baseUri}/`}`, `${baseUri.endsWith("/") ? baseUri : `${baseUri}/`}`,
ethers.utils.toUtf8Bytes(""), utils.toUtf8Bytes(""),
], ],
parse, parse,
}); });
@@ -12,7 +12,7 @@ import { ContractWrapper } from "./contract-wrapper";
import { Transaction } from "./transactions"; import { Transaction } from "./transactions";
import type { IMintableERC1155 } from "@thirdweb-dev/contracts-js"; import type { IMintableERC1155 } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, ethers } from "ethers"; import { BigNumber, type BigNumberish, constants } from "ethers";
import type { IMulticall } from "@thirdweb-dev/contracts-js"; import type { IMulticall } from "@thirdweb-dev/contracts-js";
import { TransferSingleEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/ITokenERC1155"; import { TransferSingleEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/ITokenERC1155";
import type { Erc1155 } from "./erc-1155"; import type { Erc1155 } from "./erc-1155";
@@ -124,7 +124,7 @@ export class Erc1155Mintable implements DetectableFeature {
method: "mintTo", method: "mintTo",
args: [ args: [
await resolveAddress(to), await resolveAddress(to),
ethers.constants.MaxUint256, constants.MaxUint256,
uri, uri,
metadataWithSupply.supply, metadataWithSupply.supply,
], ],
@@ -5,7 +5,7 @@ import { getPrebuiltInfo } from "../../common/legacy";
import { uploadOrExtractURIs } from "../../common/nft"; import { uploadOrExtractURIs } from "../../common/nft";
import { buildTransactionFunction } from "../../common/transactions"; import { buildTransactionFunction } from "../../common/transactions";
import { FEATURE_EDITION_SIGNATURE_MINTABLE } from "../../constants/erc1155-features"; import { FEATURE_EDITION_SIGNATURE_MINTABLE } from "../../constants/erc1155-features";
import type { NFTCollectionInitializer } from "../../contracts"; import { NFT_BASE_CONTRACT_ROLES } from "../../contracts/contractRoles";
import { import {
FilledSignaturePayload1155WithTokenId, FilledSignaturePayload1155WithTokenId,
MintRequest1155, MintRequest1155,
@@ -29,7 +29,7 @@ import type {
} from "@thirdweb-dev/contracts-js"; } from "@thirdweb-dev/contracts-js";
import { TokensMintedWithSignatureEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/ITokenERC1155"; import { TokensMintedWithSignatureEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/ITokenERC1155";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, ethers } from "ethers"; import { BigNumber, constants } from "ethers";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
/** /**
@@ -44,10 +44,7 @@ export class Erc1155SignatureMintable implements DetectableFeature {
>; >;
private storage: ThirdwebStorage; private storage: ThirdwebStorage;
private roles: private roles:
| ContractRoles< | ContractRoles<TokenERC1155, (typeof NFT_BASE_CONTRACT_ROLES)[number]>
TokenERC1155,
(typeof NFTCollectionInitializer.roles)[number]
>
| undefined; | undefined;
constructor( constructor(
@@ -55,7 +52,7 @@ export class Erc1155SignatureMintable implements DetectableFeature {
storage: ThirdwebStorage, storage: ThirdwebStorage,
roles?: ContractRoles< roles?: ContractRoles<
TokenERC1155, TokenERC1155,
(typeof NFTCollectionInitializer.roles)[number] (typeof NFT_BASE_CONTRACT_ROLES)[number]
>, >,
) { ) {
this.contractWrapper = contractWrapper; this.contractWrapper = contractWrapper;
@@ -269,7 +266,7 @@ export class Erc1155SignatureMintable implements DetectableFeature {
): Promise<SignedPayload1155> { ): Promise<SignedPayload1155> {
const payload = { const payload = {
...payloadToSign, ...payloadToSign,
tokenId: ethers.constants.MaxUint256, tokenId: constants.MaxUint256,
}; };
return this.generateFromTokenId(payload); return this.generateFromTokenId(payload);
} }
@@ -330,7 +327,7 @@ export class Erc1155SignatureMintable implements DetectableFeature {
): Promise<SignedPayload1155[]> { ): Promise<SignedPayload1155[]> {
const payloads = payloadsToSign.map((payload) => ({ const payloads = payloadsToSign.map((payload) => ({
...payload, ...payload,
tokenId: ethers.constants.MaxUint256, tokenId: constants.MaxUint256,
})); }));
return this.generateBatchFromTokenIds(payloads); return this.generateBatchFromTokenIds(payloads);
} }
@@ -50,7 +50,12 @@ import type {
TokenERC1155, TokenERC1155,
} from "@thirdweb-dev/contracts-js"; } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, BigNumberish, BytesLike, ethers } from "ethers"; import {
BigNumber,
type BigNumberish,
type BytesLike,
constants,
} from "ethers";
import { ERC1155Claimable } from "./erc-1155-claimable"; import { ERC1155Claimable } from "./erc-1155-claimable";
import { Erc1155ClaimableWithConditions } from "./erc-1155-claimable-with-conditions"; import { Erc1155ClaimableWithConditions } from "./erc-1155-claimable-with-conditions";
@@ -146,7 +151,7 @@ export class Erc1155<
})), })),
]); ]);
return { return {
owner: ethers.constants.AddressZero, owner: constants.AddressZero,
metadata, metadata,
type: "ERC1155", type: "ERC1155",
supply: supply.toString(), supply: supply.toString(),
@@ -4,7 +4,7 @@ import type { DetectableFeature } from "../interfaces/DetectableFeature";
import type { ContractWrapper } from "./contract-wrapper"; import type { ContractWrapper } from "./contract-wrapper";
import { Transaction } from "./transactions"; import { Transaction } from "./transactions";
import type { TokenERC20 } from "@thirdweb-dev/contracts-js"; import type { TokenERC20 } from "@thirdweb-dev/contracts-js";
import { ethers, BigNumber } from "ethers"; import { utils, BigNumber } from "ethers";
import { normalizePriceValue } from "../../common/currency/normalizePriceValue"; import { normalizePriceValue } from "../../common/currency/normalizePriceValue";
import { setErc20Allowance } from "../../common/currency/setErc20Allowance"; import { setErc20Allowance } from "../../common/currency/setErc20Allowance";
import type { TokenInitializer } from "../../contracts"; import type { TokenInitializer } from "../../contracts";
@@ -252,7 +252,7 @@ export class Erc20SignatureMintable implements DetectableFeature {
mintRequest.price, mintRequest.price,
mintRequest.currencyAddress, mintRequest.currencyAddress,
); );
const amountWithDecimals = ethers.utils.parseUnits( const amountWithDecimals = utils.parseUnits(
mintRequest.quantity, mintRequest.quantity,
await this.contractWrapper.readContract.decimals(), await this.contractWrapper.readContract.decimals(),
); );
+3 -4
View File
@@ -1,4 +1,3 @@
import { AmountSchema } from "../../../core/schema/shared";
import { assertEnabled } from "../../common/feature-detection/assertEnabled"; import { assertEnabled } from "../../common/feature-detection/assertEnabled";
import { detectContractFeature } from "../../common/feature-detection/detectContractFeature"; import { detectContractFeature } from "../../common/feature-detection/detectContractFeature";
import { resolveAddress } from "../../common/ens/resolveAddress"; import { resolveAddress } from "../../common/ens/resolveAddress";
@@ -34,7 +33,7 @@ import type {
IBurnableERC20, IBurnableERC20,
} from "@thirdweb-dev/contracts-js"; } from "@thirdweb-dev/contracts-js";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { ethers, BigNumber, BigNumberish } from "ethers"; import { BigNumber, BigNumberish } from "ethers";
import { fetchCurrencyMetadata } from "../../common/currency/fetchCurrencyMetadata"; import { fetchCurrencyMetadata } from "../../common/currency/fetchCurrencyMetadata";
import { fetchCurrencyValue } from "../../common/currency/fetchCurrencyValue"; import { fetchCurrencyValue } from "../../common/currency/fetchCurrencyValue";
@@ -42,6 +41,7 @@ import { Erc20Burnable } from "./erc-20-burnable";
import { Erc20Droppable } from "./erc-20-droppable"; import { Erc20Droppable } from "./erc-20-droppable";
import { Erc20Mintable } from "./erc-20-mintable"; import { Erc20Mintable } from "./erc-20-mintable";
import { Erc20SignatureMintable } from "./erc-20-signature-mintable"; import { Erc20SignatureMintable } from "./erc-20-signature-mintable";
import { normalizeAmount } from "../../common/currency/normalizeAmount";
/** /**
* Standard ERC20 Token functions * Standard ERC20 Token functions
@@ -624,8 +624,7 @@ export class Erc20<
* @param amount * @param amount
*/ */
public async normalizeAmount(amount: Amount): Promise<BigNumber> { public async normalizeAmount(amount: Amount): Promise<BigNumber> {
const decimals = await this.contractWrapper.readContract.decimals(); return normalizeAmount(this.contractWrapper, amount);
return ethers.utils.parseUnits(AmountSchema.parse(amount), decimals);
} }
/** /**
@@ -2,7 +2,7 @@ import { isFileOrBuffer, type ThirdwebStorage } from "@thirdweb-dev/storage";
import { FEATURE_NFT_SHARED_METADATA } from "../../constants/erc721-features"; import { FEATURE_NFT_SHARED_METADATA } from "../../constants/erc721-features";
import { DetectableFeature } from "../interfaces/DetectableFeature"; import { DetectableFeature } from "../interfaces/DetectableFeature";
import { ContractWrapper } from "./contract-wrapper"; import { ContractWrapper } from "./contract-wrapper";
import type { ISharedMetadata } from "@thirdweb-dev/contracts-js"; import type { SharedMetadata } from "@thirdweb-dev/contracts-js";
import { buildTransactionFunction } from "../../common/transactions"; import { buildTransactionFunction } from "../../common/transactions";
import { BasicNFTInput } from "../../../core/schema/nft"; import { BasicNFTInput } from "../../../core/schema/nft";
import { Transaction } from "./transactions"; import { Transaction } from "./transactions";
@@ -19,17 +19,46 @@ import { TransactionResult } from "../types";
export class Erc721SharedMetadata implements DetectableFeature { export class Erc721SharedMetadata implements DetectableFeature {
featureName = FEATURE_NFT_SHARED_METADATA.name; featureName = FEATURE_NFT_SHARED_METADATA.name;
private contractWrapper: ContractWrapper<ISharedMetadata>; private contractWrapper: ContractWrapper<SharedMetadata>;
private storage: ThirdwebStorage; private storage: ThirdwebStorage;
constructor( constructor(
contractWrapper: ContractWrapper<ISharedMetadata>, contractWrapper: ContractWrapper<SharedMetadata>,
storage: ThirdwebStorage, storage: ThirdwebStorage,
) { ) {
this.contractWrapper = contractWrapper; this.contractWrapper = contractWrapper;
this.storage = storage; this.storage = storage;
} }
/**
* Get Shared Metadata
*
* @remarks Get the shared metadata for the Open Edition NFTs.
*
* @example
* ```javascript
* const contract = await sdk.getContract("{{contract_address}}");
*
* const tx = await contract.erc721.sharedMetadata.get();
* ```
*
* @returns - The shared metadata for the Open Edition NFTs.
*/
public async get(): Promise<BasicNFTInput | undefined> {
const metadata = await this.contractWrapper.readContract.sharedMetadata();
if (metadata.every((value) => value === "")) {
return undefined;
}
return {
name: metadata.name,
description: metadata.description,
image: metadata.imageURI,
animation_url: metadata.animationURI,
};
}
/** /**
* Set Shared Metadata * Set Shared Metadata
* *
@@ -64,11 +93,16 @@ export class Erc721SharedMetadata implements DetectableFeature {
if (isFileOrBuffer(parsedMetadata.image)) { if (isFileOrBuffer(parsedMetadata.image)) {
batch.push(this.storage.upload(parsedMetadata.image)); batch.push(this.storage.upload(parsedMetadata.image));
} else if (typeof parsedMetadata.image === "string") {
batch.push(Promise.resolve(parsedMetadata.image));
} else { } else {
batch.push(Promise.resolve(undefined)); batch.push(Promise.resolve(undefined));
} }
if (isFileOrBuffer(parsedMetadata.animation_url)) { if (isFileOrBuffer(parsedMetadata.animation_url)) {
batch.push(this.storage.upload(parsedMetadata.animation_url)); batch.push(this.storage.upload(parsedMetadata.animation_url));
} else if (typeof parsedMetadata.animation_url === "string") {
batch.push(Promise.resolve(parsedMetadata.animation_url));
} else { } else {
batch.push(Promise.resolve(undefined)); batch.push(Promise.resolve(undefined));
} }
@@ -8,11 +8,13 @@ import type { ContractWrapper } from "./contract-wrapper";
import type { import type {
IERC721Enumerable, IERC721Enumerable,
IERC721Supply, IERC721Supply,
OpenEditionERC721,
} from "@thirdweb-dev/contracts-js"; } from "@thirdweb-dev/contracts-js";
import { BigNumber, constants } from "ethers"; import { BigNumber, constants } from "ethers";
import { DEFAULT_QUERY_ALL_COUNT } from "../../../core/schema/QueryParams"; import { DEFAULT_QUERY_ALL_COUNT } from "../../../core/schema/QueryParams";
import type { Erc721 } from "./erc-721"; import type { Erc721 } from "./erc-721";
import { Erc721Enumerable } from "./erc-721-enumerable"; import { Erc721Enumerable } from "./erc-721-enumerable";
import { hasFunction } from "../../common/feature-detection/hasFunction";
/** /**
* List ERC721 NFTs * List ERC721 NFTs
@@ -56,13 +58,22 @@ export class Erc721Supply implements DetectableFeature {
* @returns The NFT metadata for all NFTs queried. * @returns The NFT metadata for all NFTs queried.
*/ */
public async all(queryParams?: QueryAllParams): Promise<NFT[]> { public async all(queryParams?: QueryAllParams): Promise<NFT[]> {
const start = BigNumber.from(queryParams?.start || 0).toNumber(); let startTokenId = BigNumber.from(0);
if (hasFunction<OpenEditionERC721>("startTokenId", this.contractWrapper)) {
startTokenId = await this.contractWrapper.readContract.startTokenId();
}
const start = BigNumber.from(queryParams?.start || 0)
.add(startTokenId)
.toNumber();
const count = BigNumber.from( const count = BigNumber.from(
queryParams?.count || DEFAULT_QUERY_ALL_COUNT, queryParams?.count || DEFAULT_QUERY_ALL_COUNT,
).toNumber(); ).toNumber();
const maxSupply = await this.erc721.nextTokenIdToMint(); const maxSupply = await this.erc721.nextTokenIdToMint();
const maxId = Math.min(maxSupply.toNumber(), start + count); const maxId = Math.min(
maxSupply.add(startTokenId).toNumber(),
start + count,
);
return await Promise.all( return await Promise.all(
[...Array(maxId - start).keys()].map((i) => [...Array(maxId - start).keys()].map((i) =>
this.erc721.get((start + i).toString()), this.erc721.get((start + i).toString()),
@@ -27,7 +27,7 @@ import type {
} from "@thirdweb-dev/contracts-js"; } from "@thirdweb-dev/contracts-js";
import { TokensMintedWithSignatureEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/SignatureDrop"; import { TokensMintedWithSignatureEvent } from "@thirdweb-dev/contracts-js/dist/declarations/src/SignatureDrop";
import { ThirdwebStorage } from "@thirdweb-dev/storage"; import { ThirdwebStorage } from "@thirdweb-dev/storage";
import { BigNumber, ethers } from "ethers"; import { BigNumber, type providers } from "ethers";
import invariant from "tiny-invariant"; import invariant from "tiny-invariant";
/** /**
@@ -75,7 +75,7 @@ export class Erc721WithQuantitySignatureMintable implements DetectableFeature {
const signature = signedPayload.signature; const signature = signedPayload.signature;
const overrides = await this.contractWrapper.getCallOverrides(); const overrides = await this.contractWrapper.getCallOverrides();
const parse = (receipt: ethers.providers.TransactionReceipt) => { const parse = (receipt: providers.TransactionReceipt) => {
const t = const t =
this.contractWrapper.parseLogs<TokensMintedWithSignatureEvent>( this.contractWrapper.parseLogs<TokensMintedWithSignatureEvent>(
"TokensMintedWithSignature", "TokensMintedWithSignature",

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