Compare commits

..
Author SHA1 Message Date
github-actions[bot]andgithub-actions[bot] af21d5be36 Version Packages (#1669)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-10-02 22:55:38 +02:00
Manan Tank 54f83a5013 [wallets, react] - add signer on ThirdwebProvider (#1637) 2023-10-02 18:49:50 +00:00
iketwandElasticBottle 6a5bbfd2f5 [RN] Embedded fix textinput onfocus (#1691)
Co-authored-by: ElasticBottle <[email protected]>
2023-09-30 17:24:23 +00:00
Phillip Ho c5b3232e1a chore: Add usage check for EWS (#1690) 2023-09-30 02:57:22 +00:00
iketwandElasticBottle 5dc372fc46 [ReactNative] Adds EmbeddedWallet (email) (#1561)
Co-authored-by: ElasticBottle <[email protected]>
2023-09-29 21:51:58 +00:00
Manan Tank fd378ec3e4 [react] ConnectWallet UI Fixes / Improvements (#1687) 2023-09-29 15:46:27 +00:00
iketw 0e27f15eb9 [RN] Same color smart wallet active dot (#1685) 2023-09-28 21:49:42 +00:00
iketw 211aab9c16 [RN] UI improvements + ENS support (#1684) 2023-09-28 21:07:18 +00:00
Manan Tank eb9e9f0ce8 [react] ConnectWallet UI improvements (#1682) 2023-09-28 17:38:29 +00:00
iketw bd23cec7d1 [RN] Update guest wallet icon (#1683) 2023-09-28 17:32:57 +00:00
Joaquim Verges c7e7ec9502 [SmartWallets] Fix gas estimation for first SW transaction (#1681) 2023-09-28 16:50:33 +00:00
Kien Ngo 6897ad6502 [SDK] Performance improvement to various function for ERC721 (#1678) 2023-09-28 16:41:09 +00:00
iketw ed4172dddf [RN] Small UI improvements (#1680) 2023-09-28 16:20:09 +00:00
Kien Ngo de05c2da17 [SDK] Add unit test for ERC721 allOwners() (#1679) 2023-09-28 12:33:31 +00:00
Adam Majmudar c085d69060 [Wallets] Add support for GCP KMS (#1665) 2023-09-27 23:32:10 +00:00
iketw c2bfc77137 Downgrade sdk to patch update (#1677) 2023-09-27 23:17:00 +00:00
iketw 81797ffde3 [RN] Minor version bump (#1676) 2023-09-27 21:08:58 +00:00
iketw 69e8208538 [RN] Lots of small UI fixes (#1675) 2023-09-27 19:36:00 +00:00
Kien Ngo ee028e1209 [SDK] Improve data fetching for gas & transaction methods (#1672) 2023-09-27 18:51:24 +00:00
Joaquim Verges b16c09df75 [SDK] Fix error waiting for transaction after gasless tx (#1674) 2023-09-27 18:10:00 +00:00
iketw 879d4226f6 [CLI] Fix thirdweb create with options (#1673) 2023-09-27 17:00:24 +00:00
83905ef6c6 chore: minor code snippet fix (#1539)
Co-authored-by: Joaquim Verges <[email protected]>
Co-authored-by: Jonas Daniels <[email protected]>
2023-09-27 17:05:40 +02:00
Joaquim Verges f8c8c12ebc [README] add chains to readme table (#1671) 2023-09-27 14:58:48 +00:00
Joaquim Verges a9b4b0c5d8 [SDK] Expose proxy resolver helper function (#1670) 2023-09-27 14:44:22 +00:00
Kien Ngo d28b1c0f1e [SDK] Various improvement to data fetching in some erc721 modules (#1666) 2023-09-27 14:20:44 +00:00
Kien Ngo 96e832cc80 [SDK] Various improvement to data fetching in erc-20.ts (#1667) 2023-09-27 13:30:22 +00:00
Kien Ngo bdb2ccc7a6 [SDK] Slight improvement to getContract() (#1668) 2023-09-27 13:28:38 +00:00
127 changed files with 27284 additions and 9667 deletions
+10 -9
View File
@@ -20,15 +20,16 @@
## Packages
| Package | Description | Latest Version |
| ---------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [/sdk](./packages/sdk) | Best in class web3 SDK for Browser, Node and Mobile apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/sdk"><img src="https://img.shields.io/npm/v/@thirdweb-dev/sdk?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/wallets](./packages/wallets) | Unified web3 Wallet library to integrate any wallet into your applications. | <a href="https://www.npmjs.com/package/@thirdweb-dev/wallets"><img src="https://img.shields.io/npm/v/@thirdweb-dev/wallets?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/react](./packages/react) | Ultimate collection of React hooks for your web3 apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/react"><img src="https://img.shields.io/npm/v/@thirdweb-dev/react?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/react-native](./packages/react-native) | Ultimate collection of React hooks for your native mobile web3 apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/react-native"><img src="https://img.shields.io/npm/v/@thirdweb-dev/react-native?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/auth](./packages/auth) | Best in class wallet authentication for Node backends | <a href="https://www.npmjs.com/package/@thirdweb-dev/auth"><img src="https://img.shields.io/npm/v/@thirdweb-dev/auth?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/storage](./packages/storage) | Best in class decentralized storage SDK for Browser and Node | <a href="https://www.npmjs.com/package/@thirdweb-dev/storage"><img src="https://img.shields.io/npm/v/@thirdweb-dev/storage?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/cli](./packages/cli) | Publish and deploy smart contracts without dealing with private keys | <a href="https://www.npmjs.com/package/thirdweb"><img src="https://img.shields.io/npm/v/thirdweb?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| Package | Description | Latest Version |
| ---------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [/sdk](./packages/sdk) | Best in class web3 SDK for Browser, Node and Mobile apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/sdk"><img src="https://img.shields.io/npm/v/@thirdweb-dev/sdk?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/wallets](./packages/wallets) | Unified web3 Wallet library to integrate any wallet into your applications. | <a href="https://www.npmjs.com/package/@thirdweb-dev/wallets"><img src="https://img.shields.io/npm/v/@thirdweb-dev/wallets?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/react](./packages/react) | Ultimate collection of React hooks for your web3 apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/react"><img src="https://img.shields.io/npm/v/@thirdweb-dev/react?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/react-native](./packages/react-native) | Ultimate collection of React hooks for your native mobile web3 apps | <a href="https://www.npmjs.com/package/@thirdweb-dev/react-native"><img src="https://img.shields.io/npm/v/@thirdweb-dev/react-native?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/auth](./packages/auth) | Best in class wallet authentication for Node backends | <a href="https://www.npmjs.com/package/@thirdweb-dev/auth"><img src="https://img.shields.io/npm/v/@thirdweb-dev/auth?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/storage](./packages/storage) | Best in class decentralized storage SDK for Browser and Node | <a href="https://www.npmjs.com/package/@thirdweb-dev/storage"><img src="https://img.shields.io/npm/v/@thirdweb-dev/storage?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/cli](./packages/cli) | Publish and deploy smart contracts without dealing with private keys | <a href="https://www.npmjs.com/package/thirdweb"><img src="https://img.shields.io/npm/v/thirdweb?color=red&label=npm&logo=npm" alt="npm version"/></a> |
| [/chains](./packages/chains) | All EVM chain information as JS objects for easy handling | <a href="https://www.npmjs.com/package/@thirdweb-dev/chains"><img src="https://img.shields.io/npm/v/@thirdweb-dev/chains?color=red&label=npm&logo=npm" alt="npm version"/></a> |
## Documentation
+7
View File
@@ -1,5 +1,12 @@
# @thirdweb-dev/auth
## 3.2.44
### Patch Changes
- Updated dependencies [[`54f83a50`](https://github.com/thirdweb-dev/js/commit/54f83a5013ed65ddd5a787e13ba7e5d86625537d), [`c085d690`](https://github.com/thirdweb-dev/js/commit/c085d69060c68b3335761bdb2cc0c3e082548702), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3)]:
- @thirdweb-dev/wallets@1.3.1
## 3.2.43
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/auth",
"version": "3.2.43",
"version": "3.2.44",
"main": "dist/thirdweb-dev-auth.cjs.js",
"module": "dist/thirdweb-dev-auth.esm.js",
"browser": {
+7 -1
View File
@@ -20,7 +20,13 @@ export default {
{
"name": "Tectum explorer",
"url": "https://explorer.tectum.io",
"standard": "none"
"icon": {
"url": "ipfs://QmYvFVprVdAGJH4iHUCXGEmy7pq8MMfxEjM64SuXutz9qx",
"width": 256,
"height": 256,
"format": "png"
},
"standard": "EIP3091"
}
],
"testnet": false,
+3 -3
View File
@@ -30,9 +30,9 @@ export default {
"chainId": 1089,
"networkId": 1089,
"icon": {
"url": "ipfs://QmU83haX3TNifDDjBx6RP6ByqES1Kg9VqeJC87X9ipKyCS",
"width": 386,
"height": 397,
"url": "ipfs://QmX6XuoQDTTjYqAmdNJiieLDZSwHHyUx44yQb4E3tmHmEA",
"width": 400,
"height": 400,
"format": "png"
},
"explorers": [
+43
View File
@@ -0,0 +1,43 @@
import type { Chain } from "../src/types";
export default {
"name": "Movo Smart Chain Mainnet",
"chain": "MOVO",
"rpc": [
"https://movo-smart-chain.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://msc-rpc.movoscan.com",
"https://msc-rpc.movochain.org",
"https://msc-rpc.movoswap.com"
],
"faucets": [],
"nativeCurrency": {
"name": "Movo Smart Chain",
"symbol": "MOVO",
"decimals": 18
},
"infoURL": "https://movo.uk",
"shortName": "movo",
"chainId": 2049,
"networkId": 2049,
"slip44": 2050,
"icon": {
"url": "ipfs://QmbYjhXYych49hP6WY7C27pLGmSigSN35XYyocd5ftBew7",
"width": 800,
"height": 800,
"format": "png"
},
"explorers": [
{
"name": "movoscan",
"url": "https://movoscan.com",
"icon": {
"url": "ipfs://QmPqa6cJ92t4eQMgYxmVs6yr8t53ZgzchRDwz2zd2VFUwF",
"width": 256,
"height": 256,
"format": "png"
},
"standard": "none"
}
],
"testnet": false,
"slug": "movo-smart-chain"
} as const satisfies Chain;
+7 -7
View File
@@ -1,15 +1,15 @@
import type { Chain } from "../src/types";
export default {
"name": "The Krest Network",
"name": "Krest Network",
"chain": "Krest",
"icon": {
"url": "ipfs://bafkreid3bhzhughhjwq3rpgiic5zesj5mekqktawt646itdyqtvjxoupca",
"width": 257,
"height": 257,
"format": "svg"
"url": "ipfs://bafkreid732273ib5at7krjdl2t7lteljlepwd3tvifqge7mu7g6naxavhe",
"width": 256,
"height": 256,
"format": "png"
},
"rpc": [
"https://the-krest-network.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://krest-network.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://erpc-krest.peaq.network"
],
"faucets": [],
@@ -35,5 +35,5 @@ export default {
}
],
"testnet": false,
"slug": "the-krest-network"
"slug": "krest-network"
} as const satisfies Chain;
+36
View File
@@ -0,0 +1,36 @@
import type { Chain } from "../src/types";
export default {
"name": "Zilliqa EVM Isolated Server",
"chain": "ZIL",
"rpc": [
"https://zilliqa-evm-isolated-server.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://zilliqa-isolated-server.zilliqa.com/"
],
"faucets": [
"https://dev-wallet.zilliqa.com/faucet?network=isolated_server"
],
"nativeCurrency": {
"name": "Zilliqa",
"symbol": "ZIL",
"decimals": 18
},
"infoURL": "https://www.zilliqa.com/",
"shortName": "zil-isolated-server",
"chainId": 32990,
"networkId": 32990,
"icon": {
"url": "ipfs://QmTREXNgGtUhSoxFsrkhTe5LUnDBTKL5byaX8kpET6UuKp",
"width": 2048,
"height": 2048,
"format": "png"
},
"explorers": [
{
"name": "Zilliqa EVM Isolated Server Explorer",
"url": "https://devex.zilliqa.com/?network=https://zilliqa-isolated-server.zilliqa.com",
"standard": "none"
}
],
"testnet": false,
"slug": "zilliqa-evm-isolated-server"
} as const satisfies Chain;
+36
View File
@@ -0,0 +1,36 @@
import type { Chain } from "../src/types";
export default {
"name": "Zilliqa EVM Devnet",
"chain": "ZIL",
"rpc": [
"https://zilliqa-evm-devnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://api.devnet.zilliqa.com/"
],
"faucets": [
"https://faucet.devnet.zilliqa.com/"
],
"nativeCurrency": {
"name": "Zilliqa",
"symbol": "ZIL",
"decimals": 18
},
"infoURL": "https://www.zilliqa.com/",
"shortName": "zil-devnet",
"chainId": 33385,
"networkId": 33385,
"icon": {
"url": "ipfs://QmTREXNgGtUhSoxFsrkhTe5LUnDBTKL5byaX8kpET6UuKp",
"width": 2048,
"height": 2048,
"format": "png"
},
"explorers": [
{
"name": "Zilliqa EVM Devnet Explorer",
"url": "https://otterscan.devnet.zilliqa.com",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "zilliqa-evm-devnet"
} as const satisfies Chain;
+36
View File
@@ -0,0 +1,36 @@
import type { Chain } from "../src/types";
export default {
"name": "Zilliqa 2 EVM Devnet",
"chain": "ZIL",
"rpc": [
"https://zilliqa-2-evm-devnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://api.zq2-devnet.zilstg.dev"
],
"faucets": [
"https://faucet.zq2-devnet.zilstg.dev"
],
"nativeCurrency": {
"name": "Zilliqa",
"symbol": "ZIL",
"decimals": 18
},
"infoURL": "https://www.zilliqa.com/",
"shortName": "zq2-devnet",
"chainId": 33469,
"networkId": 33469,
"icon": {
"url": "ipfs://QmTREXNgGtUhSoxFsrkhTe5LUnDBTKL5byaX8kpET6UuKp",
"width": 2048,
"height": 2048,
"format": "png"
},
"explorers": [
{
"name": "Zilliqa 2 EVM Devnet Explorer",
"url": "https://explorer.zq2-devnet.zilstg.dev",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "zilliqa-2-evm-devnet"
} as const satisfies Chain;
+34
View File
@@ -0,0 +1,34 @@
import type { Chain } from "../src/types";
export default {
"name": "Gesoten Verse Testnet",
"chain": "Gesoten Verse",
"rpc": [
"https://gesoten-verse-testnet.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://rpc.testnet.verse.gesoten.com/"
],
"faucets": [],
"nativeCurrency": {
"name": "OAS",
"symbol": "OAS",
"decimals": 18
},
"infoURL": "https://gesoten.com/",
"shortName": "GST",
"icon": {
"url": "ipfs://Qmb7oJY9zd9sTzxNNQNTVZQz2hkd1aA94mWm4cvXfJ9QxV",
"width": 1280,
"height": 1280,
"format": "png"
},
"chainId": 42801,
"networkId": 42801,
"explorers": [
{
"name": "Gesoten Verse Testnet Explorer",
"url": "https://explorer.testnet.verse.gesoten.com",
"standard": "EIP3091"
}
],
"testnet": true,
"slug": "gesoten-verse-testnet"
} as const satisfies Chain;
+41
View File
@@ -0,0 +1,41 @@
import type { Chain } from "../src/types";
export default {
"name": "Highbury",
"chain": "HIGHBURY",
"rpc": [
"https://highbury.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://highbury.furya.io",
"https://rest.furya.io"
],
"faucets": [],
"nativeCurrency": {
"name": "Fury",
"symbol": "FURY",
"decimals": 18
},
"infoURL": "https://www.fury.black",
"shortName": "fury",
"chainId": 710,
"networkId": 710,
"icon": {
"url": "ipfs://bafkreiby27m6esbsjthmknckq5ktsaaj2z6hylzljbsmvx4fgezdra3q4m",
"width": 512,
"height": 512,
"format": "png"
},
"explorers": [
{
"name": "Furya EVM Explorer",
"url": "https://explorer.furya.io",
"standard": "EIP3091",
"icon": {
"url": "ipfs://bafkreiby27m6esbsjthmknckq5ktsaaj2z6hylzljbsmvx4fgezdra3q4m",
"width": 512,
"height": 512,
"format": "png"
}
}
],
"testnet": false,
"slug": "highbury"
} as const satisfies Chain;
+7 -1
View File
@@ -6,7 +6,13 @@ export default {
"https://canto.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://canto.slingshot.finance",
"https://canto.neobase.one",
"https://mainnode.plexnode.org:8545"
"https://mainnode.plexnode.org:8545",
"https://canto.gravitychain.io/",
"https://canto.evm.chandrastation.com/",
"https://jsonrpc.canto.nodestake.top/",
"https://canto.dexvaults.com/",
"wss://canto.gravitychain.io:8546",
"wss://canto.dexvaults.com/ws"
],
"faucets": [],
"nativeCurrency": {
+42
View File
@@ -0,0 +1,42 @@
import type { Chain } from "../src/types";
export default {
"name": "BTC20 Smart Chain",
"chain": "BTC20",
"rpc": [
"https://btc20-smart-chain.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
"https://rpc.bitcoincode.technology/"
],
"faucets": [],
"features": [
{
"name": "EIP155"
},
{
"name": "EIP1559"
}
],
"nativeCurrency": {
"name": "BTCC",
"symbol": "BTCC",
"decimals": 18
},
"infoURL": "https://bitcoincode.technology",
"shortName": "btc20",
"chainId": 963,
"networkId": 963,
"icon": {
"url": "ipfs://QmRUzDpn3xqPYnjLuZvFs2Attio9VxGRUprXEjcNQDcpe5",
"width": 375,
"height": 456,
"format": "png"
},
"explorers": [
{
"name": "blockscout",
"url": "https://scan.bitcoincode.technology",
"standard": "EIP3091"
}
],
"testnet": false,
"slug": "btc20-smart-chain"
} as const satisfies Chain;
+9 -4
View File
@@ -3,10 +3,10 @@ export default {
"name": "Agung Network",
"chain": "Agung",
"icon": {
"url": "ipfs://bafkreih6nzctk6brx5cqkylxbhvi3vsr6q5ks4th5knolkrlfp4tdia2mu",
"width": 400,
"height": 400,
"format": "svg"
"url": "ipfs://bafkreibkqdof3ztkdhgukwvkacwgrjb27e23hgz5c6mmudzu5hipyvgisa",
"width": 256,
"height": 256,
"format": "png"
},
"rpc": [
"https://agung-network.rpc.thirdweb.com/${THIRDWEB_API_KEY}",
@@ -27,6 +27,11 @@ export default {
"name": "Polkadot.js",
"url": "https://polkadot.js.org/apps/?rpc=wss://wsspc1-qa.agung.peaq.network#/explorer",
"standard": "none"
},
{
"name": "Subscan",
"url": "https://agung.subscan.io",
"standard": "none"
}
],
"testnet": false,
File diff suppressed because one or more lines are too long
+21
View File
@@ -1,5 +1,26 @@
# thirdweb
## 0.12.6
### Patch Changes
- [#1673](https://github.com/thirdweb-dev/js/pull/1673) [`879d4226`](https://github.com/thirdweb-dev/js/commit/879d4226f682795a48f37493d8fa1e6fbc1f2f7b) Thanks [@iketw](https://github.com/iketw)! - Fix thirdweb create with options
You can now correctly call:
- `npx thirdweb create --react`
- `npx thirdweb create --next`
- `npx thirdweb create --vite`
- `npx thirdweb create --node`
- `npx thirdweb create --express`
- `npx thirdweb create --pwaVite`
- `npx thirdweb create --reactNative`
- Updated dependencies [[`54f83a50`](https://github.com/thirdweb-dev/js/commit/54f83a5013ed65ddd5a787e13ba7e5d86625537d), [`a9b4b0c5`](https://github.com/thirdweb-dev/js/commit/a9b4b0c5d875dec660694466e5e322cc574bb21b), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3), [`96e832cc`](https://github.com/thirdweb-dev/js/commit/96e832cc80692da38279c53f1289265b3728cb19), [`b16c09df`](https://github.com/thirdweb-dev/js/commit/b16c09df75c7193a91b832db7d9c92612ae09357), [`6897ad65`](https://github.com/thirdweb-dev/js/commit/6897ad6502d585d55a8c7b2312b4af30663336c3), [`ee028e12`](https://github.com/thirdweb-dev/js/commit/ee028e12092fd306f076f6ea1d49a2295802dd6b), [`d28b1c0f`](https://github.com/thirdweb-dev/js/commit/d28b1c0f1e1e53eedc8f331be555e22b64fb920d), [`c085d690`](https://github.com/thirdweb-dev/js/commit/c085d69060c68b3335761bdb2cc0c3e082548702), [`de05c2da`](https://github.com/thirdweb-dev/js/commit/de05c2da174a69315f2d34dd32a811bbd9a0b604), [`bdb2ccc7`](https://github.com/thirdweb-dev/js/commit/bdb2ccc7a66c33ec5dc331b6fa792e6361769e88), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3)]:
- @thirdweb-dev/wallets@1.3.1
- @thirdweb-dev/sdk@3.10.63
- @thirdweb-dev/auth@3.2.44
## 0.12.5
### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "thirdweb",
"main": "dist/cli/index.js",
"version": "0.12.5",
"version": "0.12.6",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/cli",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
+15 -10
View File
@@ -254,12 +254,13 @@ const main = async () => {
.option("--forge", "Initialize as a Forge project.")
.option("--hardhat", "Initialize as a Hardhat project.")
.option("--extension", "Create a smart contract extension.")
.option("--cra", "Initialize as a Create React App project.")
.option("--react", "Initialize as a Create React App project.")
.option("--next", "Initialize as a Next.js project.")
.option("--vite", "Initialize as a Vite project.")
.option("--reactNative", "Initialize as a React Native project.")
.option("--express", "Initialize as a Express project.")
.option("--node", "Initialize as a Node project.")
.option("--pwaVite", "Initialize as a PWA project.")
.option(
"--use-npm",
"Explicitly tell the CLI to bootstrap the app using npm",
@@ -296,7 +297,9 @@ const main = async () => {
program
.command("deploy")
.description("Securely deploy your contract to any EVM network without having to deal with scripts, private keys, or ABIs")
.description(
"Securely deploy your contract to any EVM network without having to deal with scripts, private keys, or ABIs",
)
.option("-p, --path <project-path>", "path to project", ".")
.option("--clean", "clear the cache before building")
.option("--dry-run", "dry run (skip actually publishing)")
@@ -495,18 +498,20 @@ const main = async () => {
"Authorize your device to use the thirdweb CLI by authenticating with your wallet from our dashboard",
)
.action(async (options) => {
await loginUser({
credsConfigPath,
cliWalletPath,
tokenPath,
}, options, true);
await loginUser(
{
credsConfigPath,
cliWalletPath,
tokenPath,
},
options,
true,
);
});
program
.command("logout")
.description(
"Logout of the thirdweb CLI",
)
.description("Logout of the thirdweb CLI")
.action(async () => {
await logoutUser(credsConfigPath, tokenPath, cliWalletPath);
});
+46 -1
View File
@@ -43,6 +43,51 @@ export async function twCreate(
projectType = "extension";
}
// case where users use `npx thirdweb create --option` directly
if (!projectType && Object.keys(options).length > 0) {
if (options.react) {
projectType = "app";
language = "typescript";
framework = "cra";
}
if (options.next) {
projectType = "app";
language = "typescript";
framework = "next";
}
if (options.vite) {
projectType = "app";
language = "typescript";
framework = "vite";
}
if (options.node) {
projectType = "app";
language = "typescript";
framework = "node";
}
if (options.express) {
projectType = "app";
language = "typescript";
framework = "express";
}
if (options.pwaVite) {
projectType = "app";
language = "typescript";
framework = "pwa-vite";
}
if (options.reactNative) {
projectType = "app";
language = "typescript";
framework = "react-native";
}
}
if (projectType === "app") {
if (options.typescript) {
language = "typescript";
@@ -54,7 +99,7 @@ export async function twCreate(
if (options.next) {
framework = "next";
}
if (options.cra) {
if (options.react) {
framework = "cra";
}
if (options.vite) {
+9
View File
@@ -1,5 +1,14 @@
# @thirdweb-dev/react-core
## 3.16.1
### Patch Changes
- Updated dependencies [[`54f83a50`](https://github.com/thirdweb-dev/js/commit/54f83a5013ed65ddd5a787e13ba7e5d86625537d), [`a9b4b0c5`](https://github.com/thirdweb-dev/js/commit/a9b4b0c5d875dec660694466e5e322cc574bb21b), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3), [`96e832cc`](https://github.com/thirdweb-dev/js/commit/96e832cc80692da38279c53f1289265b3728cb19), [`b16c09df`](https://github.com/thirdweb-dev/js/commit/b16c09df75c7193a91b832db7d9c92612ae09357), [`6897ad65`](https://github.com/thirdweb-dev/js/commit/6897ad6502d585d55a8c7b2312b4af30663336c3), [`ee028e12`](https://github.com/thirdweb-dev/js/commit/ee028e12092fd306f076f6ea1d49a2295802dd6b), [`d28b1c0f`](https://github.com/thirdweb-dev/js/commit/d28b1c0f1e1e53eedc8f331be555e22b64fb920d), [`c085d690`](https://github.com/thirdweb-dev/js/commit/c085d69060c68b3335761bdb2cc0c3e082548702), [`de05c2da`](https://github.com/thirdweb-dev/js/commit/de05c2da174a69315f2d34dd32a811bbd9a0b604), [`bdb2ccc7`](https://github.com/thirdweb-dev/js/commit/bdb2ccc7a66c33ec5dc331b6fa792e6361769e88), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3)]:
- @thirdweb-dev/wallets@1.3.1
- @thirdweb-dev/sdk@3.10.63
- @thirdweb-dev/auth@3.2.44
## 3.16.0
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react-core",
"version": "3.16.0",
"version": "3.16.1",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-core",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -13,6 +13,7 @@ import {
createAsyncLocalStorage,
CreateAsyncStorage,
DAppMetaData,
SignerWallet,
} from "@thirdweb-dev/wallets";
import React, { useMemo } from "react";
@@ -20,7 +21,7 @@ import React, { useMemo } from "react";
* The possible props for the ThirdwebProvider.
*/
export interface ThirdwebProviderCoreProps<TChains extends Chain[]>
extends ThirdwebSDKProviderProps<TChains> {
extends Omit<ThirdwebSDKProviderProps<TChains>, "signer"> {
/**
* An array of wallets that the dApp supports
* If not provided, will default to Metamask (injected), Coinbase wallet and Device wallet
@@ -70,6 +71,8 @@ export interface ThirdwebProviderCoreProps<TChains extends Chain[]>
* @defaultValue 15000
*/
autoConnectTimeout?: number;
signerWallet?: WalletConfig<SignerWallet>;
}
export const ThirdwebProviderCore = <TChains extends Chain[]>({
@@ -153,6 +156,7 @@ export const ThirdwebProviderCore = <TChains extends Chain[]>({
autoConnectTimeout={props.autoConnectTimeout}
clientId={props.clientId}
activeChainSetExplicitly={!!props.activeChain}
signerWallet={props.signerWallet}
>
<ThirdwebSDKProviderWrapper
queryClient={props.queryClient}
@@ -10,6 +10,7 @@ import {
AsyncStorage,
ConnectParams,
CreateAsyncStorage,
SignerWallet,
walletIds,
} from "@thirdweb-dev/wallets";
import { Signer } from "ethers";
@@ -84,7 +85,7 @@ type ThirdwebWalletContextData = {
setConnectedWallet: (
wallet: WalletInstance,
params?: ConnectParams<Record<string, any>>,
) => void;
) => Promise<void>;
/**
* Get wallet config object from wallet instance
*/
@@ -109,6 +110,7 @@ export function ThirdwebWalletProvider(
autoConnectTimeout?: number;
clientId?: string;
activeChainSetExplicitly: boolean;
signerWallet?: WalletConfig<SignerWallet>;
}>,
) {
const [signer, setSigner] = useState<Signer | undefined>(undefined);
@@ -265,6 +267,11 @@ export function ThirdwebWalletProvider(
// Auto Connect
useEffect(() => {
// do not auto connect if signerWallet is given
if (props.signerWallet) {
return;
}
if (autoConnectTriggered.current) {
return;
}
@@ -375,6 +382,7 @@ export function ThirdwebWalletProvider(
activeWallet,
connectionStatus,
autoConnectTimeout,
props.signerWallet,
]);
const connectWallet = useCallback(
@@ -462,6 +470,33 @@ export function ThirdwebWalletProvider(
};
}, [activeWallet, onWalletDisconnect]);
// connect signerWallet immediately if it's passed
// and disconnect it if it's not passed
const signerConnected = useRef<typeof props.signerWallet>();
useEffect(() => {
if (!props.signerWallet) {
if (signerConnected.current) {
disconnectWallet();
signerConnected.current = undefined;
}
return;
}
if (signerConnected.current === props.signerWallet) {
return;
}
const wallet = createWalletInstance(props.signerWallet);
setConnectedWallet(wallet);
signerConnected.current = props.signerWallet;
}, [
createWalletInstance,
props.supportedWallets,
setConnectedWallet,
props.signerWallet,
disconnectWallet,
]);
return (
<ThirdwebWalletContext.Provider
value={{
@@ -140,6 +140,13 @@ export type ConnectUIProps<I extends WalletInstance = WalletInstance> = {
* This is always `compact` on React Native
*/
modalSize: "compact" | "wide";
/**
* Called when the wallet is connected but it's
* part of another wallet's connection flow.
* @param walleInstance the instance of the connected wallet
*/
onLocallyConnected?: (walleInstance: WalletInstance) => void;
};
export type SelectUIProps<I extends WalletInstance = WalletInstance> = {
@@ -1,11 +1,9 @@
import { useQuery } from "@tanstack/react-query";
import {
useAddress,
useSupportedChains,
useWalletContext,
} from "@thirdweb-dev/react-core";
import { getChainProvider } from "@thirdweb-dev/sdk/evm";
import { providers } from "ethers";
import { useAddress } from "./wallet";
import { useSupportedChains } from "./useSupportedChains";
import { useWalletContext } from "../../core/providers/thirdweb-wallet-provider";
export function useENS() {
const address = useAddress();
+1
View File
@@ -245,6 +245,7 @@ export { useSigner } from "./hooks/useSigner";
export { useSupportedChains } from "./hooks/useSupportedChains";
export { useSupportedWallet } from "./hooks/useSupportedWallet";
export { useAppURI, useSetAppURI } from "./hooks/async/app";
export { useENS } from "./hooks/useENS";
// sdk provider
export { ThirdwebSDKProvider } from "./providers/thirdweb-sdk-provider";
+43
View File
@@ -1,5 +1,48 @@
# @thirdweb-dev/react-native-compat
## 0.3.0
### Patch Changes
- [#1561](https://github.com/thirdweb-dev/js/pull/1561) [`5dc372fc`](https://github.com/thirdweb-dev/js/commit/5dc372fc460beced53fdaa3a62c780c1163bcdf2) Thanks [@iketw](https://github.com/iketw)! - Adds EmbeddedWallet (email) to React Native
You can now do:
```javascript
import { ThirdwebProvider, embeddedWallet } from "@thirdweb-dev/react-native";
<ThirdwebProvider
clientId="your-client-id"
supportedWallets={[embeddedWallet()]}
>
<App />
</ThirdwebProvider>;
```
To use the `embeddedWallet` you need to add the following dependencies to your project:
- `"amazon-cognito-identity-js": "^6.3.3"`
- react-native-quick-base64
- react-native-quick-crypto
- There's an open issue on RN > 0.72: https://github.com/margelo/react-native-quick-crypto/issues/186 which you can [fix by](https://github.com/margelo/react-native-quick-crypto/issues/186#issuecomment-1663666739) adding the following to your `android/app/build.gradle` file:
```
packagingOptions {
pickFirst 'lib/x86/libcrypto.so'
pickFirst 'lib/x86_64/libcrypto.so'
pickFirst 'lib/armeabi-v7a/libcrypto.so'
pickFirst 'lib/arm64-v8a/libcrypto.so'
}
```
- When building the iOS app in release mode for RN 0.71 you need to enable the OpenSSL framework in XCode. There are several solutions for this here:
- https://github.com/margelo/react-native-quick-crypto/issues/121#issuecomment-1369924076
- https://github.com/margelo/react-native-quick-crypto/issues/121#issuecomment-1537576444
- react-native-aes-gcm-crypto
- This package requires minSdkVersion = 26 on Android
## 0.2.62
## 0.2.61
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@thirdweb-dev/react-native-compat",
"description": "Shims for Thirdweb in React Native Projects",
"version": "0.2.62",
"version": "0.3.0",
"author": "thirdweb eng <[email protected]>",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native-compat",
"license": "Apache-2.0",
+58
View File
@@ -1,5 +1,63 @@
# @thirdweb-dev/react-native
## 0.3.0
### Minor Changes
- [#1676](https://github.com/thirdweb-dev/js/pull/1676) [`81797ffd`](https://github.com/thirdweb-dev/js/commit/81797ffde34817b457fdbf5241b1c06a13627e51) Thanks [@iketw](https://github.com/iketw)! - Minor version bump for React Native
### Patch Changes
- [#1675](https://github.com/thirdweb-dev/js/pull/1675) [`69e82085`](https://github.com/thirdweb-dev/js/commit/69e8208538886a13072b640013a8f4b46850903b) Thanks [@iketw](https://github.com/iketw)! - Lots of small UI fixes
- [#1683](https://github.com/thirdweb-dev/js/pull/1683) [`bd23cec7`](https://github.com/thirdweb-dev/js/commit/bd23cec7d1101a422e5c0abebf683595f1bac99f) Thanks [@iketw](https://github.com/iketw)! - Update guest wallet icon
- [#1561](https://github.com/thirdweb-dev/js/pull/1561) [`5dc372fc`](https://github.com/thirdweb-dev/js/commit/5dc372fc460beced53fdaa3a62c780c1163bcdf2) Thanks [@iketw](https://github.com/iketw)! - Adds EmbeddedWallet (email) to React Native
You can now do:
```javascript
import { ThirdwebProvider, embeddedWallet } from "@thirdweb-dev/react-native";
<ThirdwebProvider
clientId="your-client-id"
supportedWallets={[embeddedWallet()]}
>
<App />
</ThirdwebProvider>;
```
To use the `embeddedWallet` you need to add the following dependencies to your project:
- `"amazon-cognito-identity-js": "^6.3.3"`
- react-native-quick-base64
- react-native-quick-crypto
- There's an open issue on RN > 0.72: https://github.com/margelo/react-native-quick-crypto/issues/186 which you can [fix by](https://github.com/margelo/react-native-quick-crypto/issues/186#issuecomment-1663666739) adding the following to your `android/app/build.gradle` file:
```
packagingOptions {
pickFirst 'lib/x86/libcrypto.so'
pickFirst 'lib/x86_64/libcrypto.so'
pickFirst 'lib/armeabi-v7a/libcrypto.so'
pickFirst 'lib/arm64-v8a/libcrypto.so'
}
```
- When building the iOS app in release mode for RN 0.71 you need to enable the OpenSSL framework in XCode. There are several solutions for this here:
- https://github.com/margelo/react-native-quick-crypto/issues/121#issuecomment-1369924076
- https://github.com/margelo/react-native-quick-crypto/issues/121#issuecomment-1537576444
- react-native-aes-gcm-crypto
- This package requires minSdkVersion = 26 on Android
- [#1680](https://github.com/thirdweb-dev/js/pull/1680) [`ed4172dd`](https://github.com/thirdweb-dev/js/commit/ed4172dddf63eca19cc6cce265bdfef8b702c5d1) Thanks [@iketw](https://github.com/iketw)! - Small UI improvements
- Updated dependencies [[`54f83a50`](https://github.com/thirdweb-dev/js/commit/54f83a5013ed65ddd5a787e13ba7e5d86625537d), [`a9b4b0c5`](https://github.com/thirdweb-dev/js/commit/a9b4b0c5d875dec660694466e5e322cc574bb21b), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3), [`96e832cc`](https://github.com/thirdweb-dev/js/commit/96e832cc80692da38279c53f1289265b3728cb19), [`b16c09df`](https://github.com/thirdweb-dev/js/commit/b16c09df75c7193a91b832db7d9c92612ae09357), [`6897ad65`](https://github.com/thirdweb-dev/js/commit/6897ad6502d585d55a8c7b2312b4af30663336c3), [`ee028e12`](https://github.com/thirdweb-dev/js/commit/ee028e12092fd306f076f6ea1d49a2295802dd6b), [`d28b1c0f`](https://github.com/thirdweb-dev/js/commit/d28b1c0f1e1e53eedc8f331be555e22b64fb920d), [`c085d690`](https://github.com/thirdweb-dev/js/commit/c085d69060c68b3335761bdb2cc0c3e082548702), [`de05c2da`](https://github.com/thirdweb-dev/js/commit/de05c2da174a69315f2d34dd32a811bbd9a0b604), [`bdb2ccc7`](https://github.com/thirdweb-dev/js/commit/bdb2ccc7a66c33ec5dc331b6fa792e6361769e88), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3)]:
- @thirdweb-dev/[email protected]
- @thirdweb-dev/[email protected]
- @thirdweb-dev/[email protected]
## 0.2.62
### Patch Changes
+12 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react-native",
"version": "0.2.62",
"version": "0.3.0",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react-native",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
@@ -24,9 +24,12 @@
"android"
],
"dependencies": {
"@aws-sdk/client-lambda": "3.350.0",
"@aws-sdk/credential-providers": "3.350.0",
"@coinbase/wallet-mobile-sdk": "1.0.7",
"@magic-sdk/provider": "17.2.0",
"@magic-sdk/react-native-bare": "^18.5.0",
"@paperxyz/embedded-wallet-service-sdk": "^1.2.4",
"@shopify/restyle": "^2.4.2",
"@tanstack/react-query": "^4.33.0",
"@thirdweb-dev/chains": "workspace:*",
@@ -35,15 +38,16 @@
"@thirdweb-dev/storage": "workspace:*",
"@thirdweb-dev/wallets": "workspace:*",
"abitype": "^0.2.5",
"aws-amplify": "^5.3.8",
"expo-application": "^5.3.0",
"expo-clipboard": "^4.1.2",
"expo-document-picker": "^11.2.2",
"expo-file-system": "^15.2.2",
"expo-secure-store": "^12.1.1",
"react-native-mmkv": "2.5.1",
"react-native-modal": "^13.0.1",
"react-native-qrcode-svg": "6.2.0",
"react-native-svg": "^13.9.0",
"secrets.js-34r7h": "^2.0.2",
"tiny-invariant": "^1.2.0"
},
"devDependencies": {
@@ -72,6 +76,7 @@
"react-native": "^0.71.11",
"react-native-camera": "^4.2.1",
"react-native-device-info": "10.6.0",
"react-native-mmkv": "2.5.1",
"react-native-safe-area-context": "4.5.3",
"react-native-webview": "12.1.0",
"typescript": "^5.1.6"
@@ -80,7 +85,11 @@
"react-native-camera": "^4.2.1",
"react-native-device-info": "10.6.0",
"react-native-safe-area-context": "4.5.3",
"react-native-webview": "12.1.0"
"react-native-webview": "12.1.0",
"amazon-cognito-identity-js": "^6.3.3",
"react-native-quick-base64": "^2.0.7",
"react-native-quick-crypto": "^0.6.1",
"react-native-aes-gcm-crypto": "^0.2.2"
},
"peerDependencies": {
"ethers": ">=5.5.1 <6",
+67 -9
View File
@@ -1,16 +1,74 @@
export const LOCAL_WALLET_ICON = `<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="16" cy="16" r="16" fill="url(#paint0_linear_2103_3904)"/>
<rect x="14" y="22" width="4" height="3" fill="#E6DEFC"/>
<path d="M11 26C10.45 26 9.979 25.8218 9.587 25.4655C9.195 25.1091 8.99934 24.6812 9 24.1818V7.81818C9 7.31818 9.196 6.89 9.588 6.53364C9.98 6.17727 10.4507 5.9994 11 6H21C21.55 6 22.021 6.17818 22.413 6.53455C22.805 6.89091 23.0007 7.31879 23 7.81818V24.1818C23 24.6818 22.804 25.11 22.412 25.4664C22.02 25.8227 21.5493 26.0006 21 26H11ZM16 23.7273C16.2833 23.7273 16.521 23.64 16.713 23.4655C16.905 23.2909 17.0007 23.0751 17 22.8182C17 22.5606 16.904 22.3445 16.712 22.17C16.52 21.9955 16.2827 21.9085 16 21.9091C15.7167 21.9091 15.479 21.9964 15.287 22.1709C15.095 22.3455 14.9993 22.5612 15 22.8182C15 23.0758 15.096 23.2918 15.288 23.4664C15.48 23.6409 15.7173 23.7279 16 23.7273ZM11 17.6364C11 18.7409 11.8954 19.6364 13 19.6364H19C20.1046 19.6364 21 18.7409 21 17.6364V12.5455C21 11.4409 20.1046 10.5455 19 10.5455H13C11.8954 10.5455 11 11.4409 11 12.5455V17.6364Z" fill="black"/>
<path d="M11 26C10.45 26 9.979 25.8218 9.587 25.4655C9.195 25.1091 8.99934 24.6812 9 24.1818V7.81818C9 7.31818 9.196 6.89 9.588 6.53364C9.98 6.17727 10.4507 5.9994 11 6H21C21.55 6 22.021 6.17818 22.413 6.53455C22.805 6.89091 23.0007 7.31879 23 7.81818V24.1818C23 24.6818 22.804 25.11 22.412 25.4664C22.02 25.8227 21.5493 26.0006 21 26H11ZM16 23.7273C16.2833 23.7273 16.521 23.64 16.713 23.4655C16.905 23.2909 17.0007 23.0751 17 22.8182C17 22.5606 16.904 22.3445 16.712 22.17C16.52 21.9955 16.2827 21.9085 16 21.9091C15.7167 21.9091 15.479 21.9964 15.287 22.1709C15.095 22.3455 14.9993 22.5612 15 22.8182C15 23.0758 15.096 23.2918 15.288 23.4664C15.48 23.6409 15.7173 23.7279 16 23.7273ZM11 17.6364C11 18.7409 11.8954 19.6364 13 19.6364H19C20.1046 19.6364 21 18.7409 21 17.6364V12.5455C21 11.4409 20.1046 10.5455 19 10.5455H13C11.8954 10.5455 11 11.4409 11 12.5455V17.6364Z" fill="url(#paint1_linear_2103_3904)"/>
<rect x="11" y="8" width="10" height="16" rx="1.5" fill="#BB0FAE"/>
<rect x="13" y="9" width="6" height="2" rx="1" fill="#F8F5FF"/>
export const EMAIL_WALLET_ICON = `<svg width="48" height="48" viewBox="0 0 48 48" fill="none">
<g clip-path="url(#clip0_3589_8649)">
<rect width="48" height="48" rx="8" fill="url(#paint0_linear_3589_8649)"/>
<rect x="-1" y="-1" width="50" height="50" rx="9.8" fill="url(#paint1_linear_3589_8649)"/>
<g clip-path="url(#clip1_3589_8649)">
<path d="M24 14.25C18.6172 14.25 14.25 18.6172 14.25 24C14.25 29.3828 18.6172 33.75 24 33.75C24.8988 33.75 25.625 34.4762 25.625 35.375C25.625 36.2738 24.8988 37 24 37C16.8195 37 11 31.1805 11 24C11 16.8195 16.8195 11 24 11C31.1805 11 37 16.8195 37 24V25.625C37 28.3164 34.8164 30.5 32.125 30.5C30.6371 30.5 29.3016 29.8297 28.4078 28.7785C27.25 29.8449 25.7012 30.5 24 30.5C20.4098 30.5 17.5 27.5902 17.5 24C17.5 20.4098 20.4098 17.5 24 17.5C25.4168 17.5 26.727 17.952 27.7934 18.7238C28.0828 18.4699 28.4586 18.3125 28.875 18.3125C29.7738 18.3125 30.5 19.0387 30.5 19.9375V25.625C30.5 26.5238 31.2262 27.25 32.125 27.25C33.0238 27.25 33.75 26.5238 33.75 25.625V24C33.75 18.6172 29.3828 14.25 24 14.25ZM27.25 24C27.25 23.138 26.9076 22.3114 26.2981 21.7019C25.6886 21.0924 24.862 20.75 24 20.75C23.138 20.75 22.3114 21.0924 21.7019 21.7019C21.0924 22.3114 20.75 23.138 20.75 24C20.75 24.862 21.0924 25.6886 21.7019 26.2981C22.3114 26.9076 23.138 27.25 24 27.25C24.862 27.25 25.6886 26.9076 26.2981 26.2981C26.9076 25.6886 27.25 24.862 27.25 24Z" fill="white"/>
</g>
</g>
<defs>
<linearGradient id="paint0_linear_2103_3904" x1="15" y1="-9.12696e-08" x2="15" y2="35.5" gradientUnits="userSpaceOnUse">
<linearGradient id="paint0_linear_3589_8649" x1="25.5" y1="-6.29572e-06" x2="30.2016" y2="47.535" gradientUnits="userSpaceOnUse">
<stop stop-color="#8358BA"/>
<stop offset="1" stop-color="#7B1CF7"/>
</linearGradient>
<linearGradient id="paint1_linear_3589_8649" x1="25.5625" y1="-1.00001" x2="30.46" y2="48.5156" gradientUnits="userSpaceOnUse">
<stop stop-color="#8358BA"/>
<stop offset="1" stop-color="#7B1CF7"/>
</linearGradient>
<clipPath id="clip0_3589_8649">
<rect width="48" height="48" rx="8" fill="white"/>
</clipPath>
<clipPath id="clip1_3589_8649">
<rect width="26" height="26" fill="white" transform="translate(11 11)"/>
</clipPath>
</defs>
</svg>`;
export const SMART_WALLET_ICON = `<svg width="80" height="80" viewBox="0 0 80 80" fill="none">
<rect width="80" height="80" rx="12" fill="url(#paint0_linear_1_91)"/>
<path d="M39.9969 18L40.2333 18.0156L40.3513 18.0333L40.4736 18.0622L40.6958 18.1378C40.8494 18.2006 40.9953 18.2842 41.1305 18.3867L41.3387 18.5689L41.8493 19.0533C45.8891 22.7768 50.9947 24.7762 56.2458 24.6911L56.9307 24.6689C57.3783 24.6462 57.82 24.7909 58.1849 25.0798C58.5498 25.3687 58.8167 25.785 58.9431 26.2622C59.9271 29.9769 60.2283 33.8731 59.8287 37.7194C59.4289 41.5658 58.3367 45.2836 56.6165 48.6523C54.8965 52.0207 52.5836 54.9714 49.8156 57.3285C47.0476 59.6856 43.8809 61.4012 40.5036 62.3734C40.174 62.4683 39.828 62.4683 39.4982 62.3734C36.1209 61.4014 32.9538 59.686 30.1856 57.3289C27.4176 54.9718 25.1045 52.0214 23.3842 48.6529C21.6638 45.2843 20.5713 41.5662 20.1715 37.7198C19.7717 33.8734 20.0727 29.9769 21.0567 26.2622C21.1831 25.785 21.4501 25.3687 21.815 25.0798C22.1799 24.7909 22.6215 24.6462 23.0693 24.6689C28.5513 24.947 33.9293 22.9444 38.1507 19.0533L38.6773 18.5533L38.8696 18.3867C39.0047 18.2842 39.1505 18.2006 39.304 18.1378L39.5282 18.0622C39.6069 18.0412 39.6865 18.0256 39.7667 18.0156L39.9969 18ZM40.0009 33.5556C38.9905 33.5551 38.0173 33.9787 37.2765 34.7411C36.5356 35.5036 36.0816 36.5485 36.0058 37.6667L35.9958 38L36.0058 38.3334C36.0551 39.0547 36.2625 39.7518 36.6098 40.364C36.9569 40.9762 37.4336 41.4851 37.9985 41.8467V45.7778L38.0125 46.0378C38.0727 46.6003 38.3242 47.1158 38.7156 47.4794C39.1071 47.8429 39.6087 48.0269 40.1182 47.9938C40.6278 47.9605 41.1067 47.7127 41.4571 47.3009C41.8076 46.8889 42.0029 46.3442 42.0036 45.7778L42.0056 41.8489C42.7691 41.3596 43.366 40.6042 43.7034 39.7002C44.0407 38.796 44.0996 37.7938 43.8711 36.8487C43.6427 35.9036 43.1396 35.0685 42.4398 34.4731C41.74 33.8776 40.8827 33.5551 40.0009 33.5556Z" fill="url(#paint1_linear_1_91)"/>
<defs>
<linearGradient id="paint0_linear_1_91" x1="40" y1="0" x2="40" y2="80" gradientUnits="userSpaceOnUse">
<stop stop-color="#8356BD"/>
<stop offset="1" stop-color="#7C20F4"/>
</linearGradient>
<linearGradient id="paint1_linear_1_91" x1="40" y1="18" x2="40" y2="62.4445" gradientUnits="userSpaceOnUse">
<stop stop-color="white"/>
<stop offset="1" stop-color="#E1D8FB"/>
</linearGradient>
</defs>
</svg>`;
export const WALLETCONNECT_ICON = `<svg width="80" height="80" viewBox="0 0 80 80" fill="none">
<rect width="80" height="80" rx="12" fill="#1C7DFC"/>
<rect width="80" height="80" rx="12" fill="url(#paint0_radial_1_46)"/>
<path d="M26.4227 31.4731C33.9171 24.1756 46.0829 24.1756 53.5773 31.4731L54.4796 32.358C54.858 32.7207 54.858 33.3155 54.4796 33.6782L51.3945 36.6813C51.2053 36.8699 50.8997 36.8699 50.7105 36.6813L49.4736 35.4772C44.2347 30.385 35.7653 30.385 30.5264 35.4772L29.2021 36.7684C29.013 36.957 28.7074 36.957 28.5182 36.7684L25.4331 33.7653C25.0547 33.4026 25.0547 32.8078 25.4331 32.4451L26.4227 31.4731ZM59.9658 37.6824L62.7162 40.3518C63.0946 40.7145 63.0946 41.3093 62.7162 41.672L50.3322 53.728C49.9538 54.0907 49.3426 54.0907 48.9788 53.728L40.1892 45.1684C40.1019 45.0813 39.9418 45.0813 39.8545 45.1684L31.0649 53.728C30.6865 54.0907 30.0753 54.0907 29.7115 53.728L17.2838 41.672C16.9054 41.3093 16.9054 40.7145 17.2838 40.3518L20.0342 37.6824C20.4125 37.3197 21.0237 37.3197 21.3875 37.6824L30.1772 46.242C30.2645 46.329 30.4245 46.329 30.5119 46.242L39.3015 37.6824C39.6799 37.3197 40.291 37.3197 40.6549 37.6824L49.4445 46.242C49.5318 46.329 49.6919 46.329 49.7792 46.242L58.5688 37.6824C58.9763 37.3197 59.5875 37.3197 59.9658 37.6824Z" fill="white"/>
<defs>
<radialGradient id="paint0_radial_1_46" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(0.000247955 40.0012) scale(80)">
<stop stop-color="#5D9DF6"/>
<stop offset="1" stop-color="#006FFF"/>
</radialGradient>
</defs>
</svg>`;
export const LOCAL_WALLET_ICON = `<svg width="48" height="48" viewBox="0 0 48 48" fill="none">
<rect width="48" height="48" rx="7.2" fill="url(#paint0_linear_4221_3214)"/>
<rect width="48" height="48" rx="7.2" fill="url(#paint1_linear_4221_3214)"/>
<path d="M16.5 39C15.675 39 14.9685 38.7327 14.3805 38.1982C13.7925 37.6636 13.499 37.0218 13.5 36.2727V11.7273C13.5 10.9773 13.794 10.335 14.382 9.80046C14.97 9.26591 15.676 8.99909 16.5 9H31.5C32.325 9 33.0315 9.26728 33.6195 9.80182C34.2075 10.3364 34.501 10.9782 34.5 11.7273V36.2727C34.5 37.0227 34.206 37.665 33.618 38.1995C33.03 38.7341 32.324 39.0009 31.5 39H16.5ZM24 35.5909C24.425 35.5909 24.7815 35.46 25.0695 35.1982C25.3575 34.9364 25.501 34.6127 25.5 34.2273C25.5 33.8409 25.356 33.5168 25.068 33.255C24.78 32.9932 24.424 32.8627 24 32.8636C23.575 32.8636 23.2185 32.9945 22.9305 33.2564C22.6425 33.5182 22.499 33.8418 22.5 34.2273C22.5 34.6136 22.644 34.9377 22.932 35.1995C23.22 35.4614 23.576 35.5918 24 35.5909ZM16.5 24.4545C16.5 27.216 18.7386 29.4545 21.5 29.4545H26.5C29.2614 29.4545 31.5 27.216 31.5 24.4545V20.8182C31.5 18.0568 29.2614 15.8182 26.5 15.8182H21.5C18.7386 15.8182 16.5 18.0568 16.5 20.8182V24.4545Z" fill="black"/>
<path d="M16.5 39C15.675 39 14.9685 38.7327 14.3805 38.1982C13.7925 37.6636 13.499 37.0218 13.5 36.2727V11.7273C13.5 10.9773 13.794 10.335 14.382 9.80046C14.97 9.26591 15.676 8.99909 16.5 9H31.5C32.325 9 33.0315 9.26728 33.6195 9.80182C34.2075 10.3364 34.501 10.9782 34.5 11.7273V36.2727C34.5 37.0227 34.206 37.665 33.618 38.1995C33.03 38.7341 32.324 39.0009 31.5 39H16.5ZM24 35.5909C24.425 35.5909 24.7815 35.46 25.0695 35.1982C25.3575 34.9364 25.501 34.6127 25.5 34.2273C25.5 33.8409 25.356 33.5168 25.068 33.255C24.78 32.9932 24.424 32.8627 24 32.8636C23.575 32.8636 23.2185 32.9945 22.9305 33.2564C22.6425 33.5182 22.499 33.8418 22.5 34.2273C22.5 34.6136 22.644 34.9377 22.932 35.1995C23.22 35.4614 23.576 35.5918 24 35.5909ZM16.5 24.4545C16.5 27.216 18.7386 29.4545 21.5 29.4545H26.5C29.2614 29.4545 31.5 27.216 31.5 24.4545V20.8182C31.5 18.0568 29.2614 15.8182 26.5 15.8182H21.5C18.7386 15.8182 16.5 18.0568 16.5 20.8182V24.4545Z" fill="url(#paint2_linear_4221_3214)"/>
<rect x="16.5" y="12" width="15" height="24" rx="2.25" fill="#B70FAF"/>
<rect x="19.5" y="13.5" width="9" height="3" rx="1.5" fill="#F8F5FF"/>
<defs>
<linearGradient id="paint0_linear_4221_3214" x1="25.5" y1="-6.29572e-06" x2="30.2016" y2="47.535" gradientUnits="userSpaceOnUse">
<stop stop-color="#8358BA"/>
<stop offset="0.422496" stop-color="#803FD4"/>
<stop offset="1" stop-color="#7B1CF7"/>
</linearGradient>
<linearGradient id="paint1_linear_4221_3214" x1="22.5" y1="-1.36904e-07" x2="22.5" y2="53.25" gradientUnits="userSpaceOnUse">
<stop stop-color="#D311AA"/>
<stop offset="1" stop-color="#8409B7"/>
</linearGradient>
<linearGradient id="paint1_linear_2103_3904" x1="16" y1="6" x2="16" y2="26" gradientUnits="userSpaceOnUse">
<linearGradient id="paint2_linear_4221_3214" x1="24" y1="9" x2="24" y2="39" gradientUnits="userSpaceOnUse">
<stop stop-color="white"/>
<stop offset="1" stop-color="#E1D8FB"/>
</linearGradient>
@@ -72,8 +72,10 @@ export const ConnectWallet = ({
theme,
buttonTitle,
modalTitle,
modalTitleIconUrl,
extraRows,
hideTestnetFaucet,
displayBalanceToken,
switchToActiveChain,
termsOfServiceUrl,
privacyPolicyUrl,
@@ -151,12 +153,14 @@ export const ConnectWallet = ({
extraRows={extraRows}
hideTestnetFaucet={hideTestnetFaucet}
supportedTokens={supportedTokensMemo}
displayBalanceToken={displayBalanceToken}
/>
)
) : (
<ConnectWalletButton
modalTitle={modalTitle}
buttonTitle={buttonTitle}
modalTitleIconUrl={modalTitleIconUrl}
theme={theme}
termsOfServiceUrl={termsOfServiceUrl}
privacyPolicyUrl={privacyPolicyUrl}
@@ -27,6 +27,8 @@ import TransactionIcon from "../../assets/transaction";
import { ReceiveButton } from "../ReceiveButton";
import { SendButton } from "../SendFunds/SendButton";
import { SupportedTokens } from "../SendFunds/defaultTokens";
import { ActiveDot } from "../base";
import { EmbeddedWallet } from "../../wallets/wallets/embedded/EmbeddedWallet";
const MODAL_HEIGHT = Dimensions.get("window").height * 0.7;
const DEVICE_WIDTH = Dimensions.get("window").width;
@@ -62,6 +64,19 @@ export const ConnectWalletDetailsModal = ({
? displayBalanceToken[chain?.chainId]
: undefined;
const [isSmartWalletDeployed, setIsSmartWalletDeployed] = useState(false);
useEffect(() => {
if (activeWallet && activeWallet.walletId === walletIds.smartWallet) {
const connectedSmartWallet = activeWallet as SmartWallet;
connectedSmartWallet.isDeployed().then((isDeployed) => {
setIsSmartWalletDeployed(isDeployed);
});
} else {
setIsSmartWalletDeployed(false);
}
}, [activeWallet]);
useEffect(() => {
const timeout = setTimeout(() => {
if (addressCopied) {
@@ -165,7 +180,7 @@ export const ConnectWalletDetailsModal = ({
/>
{activeWallet?.walletId === LocalWallet.id ? (
<Text variant="error" textAlign="left">
<Text variant="error" textAlign="left" mb="sm">
{
"This is a temporary guest wallet. Download a backup if you don't want to lose access to it."
}
@@ -199,6 +214,38 @@ export const ConnectWalletDetailsModal = ({
onDisconnectPress={onDisconnectPress}
onAddressCopied={onAddressCopied}
/>
{activeWallet?.walletId === SmartWallet.id ? (
<BaseButton
disabled={!isSmartWalletDeployed}
onPress={() => {
Linking.openURL(
`https://thirdweb.com/${chain?.slug}/${address}/account`,
);
}}
flexDirection="row"
alignItems="center"
justifyContent="space-between"
mt="md"
>
<Box flexDirection="row" alignItems="center">
<ActiveDot width={10} height={10} />
<Text variant="bodySmallSecondary" ml="xxs">
Connected to a Smart Wallet
</Text>
</Box>
{isSmartWalletDeployed ? (
<RightArrowIcon width={10} height={10} />
) : null}
</BaseButton>
) : null}
{activeWallet?.walletId === EmbeddedWallet.id ? (
<Box flexDirection="row" alignItems="center" mt="md">
<ActiveDot width={10} height={10} />
<Text variant="bodySmallSecondary" ml="xxs">
{(activeWallet as EmbeddedWallet).getEmail()}
</Text>
</Box>
) : null}
<Box flexDirection="row" justifyContent="space-evenly" mt="md">
<SendButton supportedTokens={supportedTokens} />
<ReceiveButton />
@@ -16,7 +16,6 @@ import * as FileSystem from "expo-file-system";
import { SmartWallet } from "@thirdweb-dev/wallets";
import { usePersonalWalletAddress } from "../../wallets/hooks/usePersonalWalletAddress";
import { shortenWalletAddress } from "../../utils/addresses";
import { WalletIcon } from "../base/WalletIcon";
import { LocalWallet } from "../../wallets/wallets/LocalWallet";
import { TWModal } from "../base/modal/TWModal";
@@ -150,13 +149,10 @@ export const ExportLocalWalletModal = ({
borderRadius="md"
p="lg"
>
<Box flexDirection="row" justifyContent="space-between" mb="sm">
<WalletIcon size={32} iconUri={LocalWallet.meta.iconURL} />
<ModalHeaderTextClose flex={1} onClose={onCloseInternal} />
</Box>
<Text variant="header" textAlign="left">
Backup your Wallet
</Text>
<ModalHeaderTextClose
onClose={onCloseInternal}
headerText="Backup your Wallet"
/>
<Text variant="subHeader" mt="md" textAlign="left">
{
"This will download a JSON file containing your wallet information onto your device encrypted with the password."
@@ -107,7 +107,7 @@ export const SmartWalletAdditionalActions = ({
color={theme.colors.iconPrimary}
/>
</BaseButton>
<Text variant="error" textAlign="left">
<Text variant="error" textAlign="left" mb="sm">
{
"This is a temporary guest wallet. Download a backup if you don't want to loose access to it."
}
@@ -2,14 +2,15 @@ import { AddressDisplay } from "../base/AddressDisplay";
import BaseButton from "../base/BaseButton";
import Text from "../base/Text";
import { WalletIcon } from "../base/WalletIcon";
import { useWallet } from "@thirdweb-dev/react-core";
import { useENS, useWallet } from "@thirdweb-dev/react-core";
import { StyleSheet } from "react-native";
import { LocalWallet } from "@thirdweb-dev/wallets";
import { LocalWallet, walletIds } from "@thirdweb-dev/wallets";
import Box from "../base/Box";
import { ConnectWalletDetailsModal } from "./ConnectWalletDetailsModal";
import { useState } from "react";
import { useMemo, useState } from "react";
import { TextBalance } from "../base/TextBalance";
import { SupportedTokens } from "../SendFunds/defaultTokens";
import { SMART_WALLET_ICON } from "../../assets/svgs";
export type ConnectWalletDetailsProps = {
address?: string;
@@ -46,11 +47,23 @@ export const WalletDetailsButton = ({
}: ConnectWalletDetailsProps) => {
const activeWallet = useWallet();
const [isModalVisible, setIsModalVisible] = useState(false);
const ensQuery = useENS();
const onPress = () => {
setIsModalVisible(!isModalVisible);
};
const ens = useMemo(() => ensQuery.data?.ens, [ensQuery.data?.ens]);
const avatarUrl = useMemo(
() => ensQuery.data?.avatarUrl,
[ensQuery.data?.avatarUrl],
);
const walletIconUrl =
activeWallet?.walletId === walletIds.smartWallet
? SMART_WALLET_ICON
: activeWallet?.getMeta().iconURL || "";
return (
<>
<ConnectWalletDetailsModal
@@ -71,16 +84,20 @@ export const WalletDetailsButton = ({
style={styles.walletDetails}
onPress={onPress}
>
<Box flex={1} flexDirection="row" justifyContent="flex-start">
<WalletIcon
size={32}
iconUri={activeWallet?.getMeta().iconURL || ""}
/>
<Box
flex={1}
flexDirection="row"
alignContent="center"
justifyContent="flex-start"
>
<WalletIcon size={32} iconUri={avatarUrl || walletIconUrl} />
<Box ml="md" justifyContent="center" alignItems="flex-start">
{activeWallet?.walletId === LocalWallet.id ? (
<Text variant="bodySmall" color="red">
Guest
</Text>
) : ens ? (
<Text variant="bodySmall">{ens}</Text>
) : (
<AddressDisplay
variant="bodySmall"
@@ -3,13 +3,16 @@ import { useAppTheme } from "../../styles/hooks";
import { AddressDisplay } from "../base/AddressDisplay";
import BaseButton from "../base/BaseButton";
import { WalletIcon } from "../base/WalletIcon";
import { useWallet } from "@thirdweb-dev/react-core";
import { useENS, useWallet } from "@thirdweb-dev/react-core";
import { ActivityIndicator, StyleSheet, View } from "react-native";
import * as Clipboard from "expo-clipboard";
import Box from "../base/Box";
import CopyIcon from "../../assets/copy";
import { useState } from "react";
import { useMemo, useState } from "react";
import { TextBalance } from "../base/TextBalance";
import { walletIds } from "@thirdweb-dev/wallets";
import { SMART_WALLET_ICON } from "../../assets/svgs";
import Text from "../base/Text";
interface WalletDetailsModalHeaderProps {
address?: string;
@@ -28,6 +31,7 @@ export const WalletDetailsModalHeader = ({
const theme = useAppTheme();
const activeWallet = useWallet();
const [showLoading, setShowLoading] = useState(false);
const ensQuery = useENS();
const onAddressPress = async () => {
if (!address) {
@@ -44,10 +48,21 @@ export const WalletDetailsModalHeader = ({
}, 0);
};
const ens = useMemo(() => ensQuery.data?.ens, [ensQuery.data?.ens]);
const avatarUrl = useMemo(
() => ensQuery.data?.avatarUrl,
[ensQuery.data?.avatarUrl],
);
const walletIconUrl =
activeWallet?.walletId === walletIds.smartWallet
? SMART_WALLET_ICON
: activeWallet?.getMeta().iconURL || "";
return (
<>
<View style={styles.header}>
<WalletIcon size={40} iconUri={activeWallet?.getMeta().iconURL || ""} />
<WalletIcon size={40} iconUri={avatarUrl || walletIconUrl} />
<BaseButton
flex={1}
justifyContent="flex-start"
@@ -61,7 +76,13 @@ export const WalletDetailsModalHeader = ({
justifyContent="center"
alignItems="center"
>
<AddressDisplay mr="xs" address={address} extraShort={false} />
{ens ? (
<Text mr="xs" variant="bodyLarge">
{ens}
</Text>
) : (
<AddressDisplay mr="xs" address={address} extraShort={false} />
)}
<CopyIcon
width={14}
height={14}
@@ -7,7 +7,7 @@ import Text from "../../base/Text";
import ThirdwebLogo from "../../../assets/thirdweb-logo";
import { useAppTheme } from "../../../styles/hooks";
import { ChooseWalletContent } from "./ChooseWalletContent";
import { BaseButton, ImageSvgUri } from "../../base";
import { BaseButton, ImageSvgUri, WalletButton } from "../../base";
import { ActivityIndicator, Linking } from "react-native";
import { useTheme } from "@shopify/restyle";
@@ -18,6 +18,7 @@ export type ChooseWalletProps = {
onClose: () => void;
wallets: WalletConfig<any>[];
excludeWalletIds?: string[];
modalTitleIconUrl?: string;
termsOfServiceUrl?: string;
privacyPolicyUrl?: string;
};
@@ -27,6 +28,7 @@ export function ChooseWallet({
subHeaderText,
wallets,
onChooseWallet,
modalTitleIconUrl,
onClose,
excludeWalletIds = [],
termsOfServiceUrl,
@@ -38,11 +40,14 @@ export function ChooseWallet({
const [isConnectAWalletEnabled, setIsConnectAWalletEnabled] = useState(false);
const guestWallet = wallets.find((w) => w.id === walletIds.localWallet);
const emailWallet = wallets.find((w) => w.id === walletIds.magicLink);
const emailWallet = wallets.find(
(w) => w.id === walletIds.magicLink || w.id === walletIds.embeddedWallet,
);
const connectionWallets = wallets
.filter(
(wallet) =>
wallet.id !== walletIds.magicLink &&
wallet.id !== walletIds.embeddedWallet &&
wallet.id !== walletIds.localWallet,
)
.slice(0, 2);
@@ -62,6 +67,10 @@ export function ChooseWallet({
setIsConnectAWalletEnabled(true);
};
const onSingleWalletPress = () => {
onChooseWallet(connectionWallets[0]);
};
const onBackPress = () => {
setIsConnectAWalletEnabled(false);
};
@@ -98,11 +107,21 @@ export function ChooseWallet({
alignContent="center"
justifyContent="center"
>
<ThirdwebLogo
width={26}
height={15}
color={theme.colors.backgroundInverted}
/>
{modalTitleIconUrl !== undefined ? (
modalTitleIconUrl.length === 0 ? null : (
<ImageSvgUri
width={26}
height={15}
imageUrl={modalTitleIconUrl}
/>
)
) : (
<ThirdwebLogo
width={26}
height={15}
color={theme.colors.backgroundInverted}
/>
)}
<Text
variant="header"
ml="xxs"
@@ -125,6 +144,7 @@ export function ChooseWallet({
...excludeWalletIds,
walletIds.localWallet,
walletIds.magicLink,
walletIds.embeddedWallet,
]}
onChooseWallet={onChooseWallet}
/>
@@ -177,38 +197,50 @@ export function ChooseWallet({
{emailWallet &&
!isConnectAWalletEnabled &&
connectionWallets.length > 0 ? (
<BaseButton
marginHorizontal="xl"
justifyContent="center"
borderRadius="lg"
paddingVertical="xmd"
borderColor="border"
flexDirection="row"
alignItems="center"
borderWidth={1}
onPress={onConnectAWalletPress}
>
{connectionWallets.map((wallet) => {
return (
<Box key={wallet.meta.name} mr="xxs">
<ImageSvgUri
height={20}
width={20}
imageUrl={wallet.meta.iconURL}
/>
</Box>
);
})}
<Text variant="bodySmall" fontWeight="700">
Connect a wallet
</Text>
</BaseButton>
connectionWallets.length === 1 ? (
<WalletButton
marginHorizontal="xl"
paddingHorizontal="none"
paddingVertical="none"
mb="md"
walletIconUrl={connectionWallets[0].meta.iconURL}
name={connectionWallets[0].meta.name}
onPress={onSingleWalletPress}
/>
) : (
<BaseButton
marginHorizontal="xl"
justifyContent="center"
borderRadius="lg"
paddingVertical="md"
borderColor="border"
flexDirection="row"
alignItems="center"
borderWidth={1}
onPress={onConnectAWalletPress}
>
{connectionWallets.map((wallet) => {
return (
<Box key={wallet.meta.name} mr="xxs">
<ImageSvgUri
height={20}
width={20}
imageUrl={wallet.meta.iconURL}
/>
</Box>
);
})}
<Text variant="bodySmall" fontWeight="700">
Connect a wallet
</Text>
</BaseButton>
)
) : null}
{guestWallet ? (
<BaseButton
marginHorizontal="xl"
mt="sm"
paddingVertical="xmd"
paddingVertical="md"
justifyContent="center"
borderRadius="lg"
borderColor="border"
@@ -216,7 +248,10 @@ export function ChooseWallet({
onPress={onContinueAsGuestPress}
>
{isConnecting ? (
<ActivityIndicator size={"small"} />
<ActivityIndicator
size={"small"}
color={theme.colors.textPrimary}
/>
) : (
<Text variant="bodySmall" fontWeight="700">
Continue as guest
@@ -40,7 +40,8 @@ export const ChooseWalletContent = ({
<View style={{ flexDirection: "column", maxHeight: MAX_HEIGHT }}>
<ScrollView
style={{
marginVertical: 16,
marginTop: 16,
paddingBottom: 16,
paddingHorizontal: 16,
}}
>
@@ -74,6 +75,7 @@ export const ChooseWalletContent = ({
recommended={item.recommended}
onPress={() => onChooseWallet(item)}
mb={marginBottom}
paddingVertical="xxs"
/>
)}
</Box>
@@ -18,6 +18,12 @@ export type ConnectWalletButtonProps = {
* @default "Choose your wallet"
*/
modalTitle?: string;
/**
* Replace the thirdweb icon next to modalTitle and set your own iconUrl
*
* Set to empty string to hide the icon
*/
modalTitleIconUrl?: string;
/**
* Set a custom terms of service url
*/
@@ -31,6 +37,7 @@ export type ConnectWalletButtonProps = {
export const ConnectWalletButton = ({
modalTitle,
modalTitleIconUrl,
termsOfServiceUrl,
privacyPolicyUrl,
buttonTitle,
@@ -72,6 +79,7 @@ export const ConnectWalletButton = ({
view: "ConnectWalletFlow",
data: {
modalTitle,
modalTitleIconUrl,
termsOfServiceUrl,
privacyPolicyUrl,
walletConfig:
@@ -16,9 +16,13 @@ import { useAppTheme } from "../../styles/hooks";
export const ConnectWalletFlow = () => {
const { modalState, setModalState } = useModalState();
const { modalTitle, privacyPolicyUrl, termsOfServiceUrl, walletConfig } = (
modalState as ConnectWalletFlowModal
).data;
const {
modalTitle,
modalTitleIconUrl,
privacyPolicyUrl,
termsOfServiceUrl,
walletConfig,
} = (modalState as ConnectWalletFlowModal).data;
const [modalVisible, setModalVisible] = useState(false);
const [activeWallet, setActiveWallet] = useState<WalletConfig | undefined>();
@@ -56,7 +60,7 @@ export const ConnectWalletFlow = () => {
const onChooseWallet = useCallback(
(wallet: WalletConfig, data?: any) => {
setActiveWallet(() => wallet);
setActiveWallet(wallet);
setSelectionData(data);
// If the wallet has no custom connect UI, then connect it
@@ -69,8 +73,14 @@ export const ConnectWalletFlow = () => {
useEffect(() => {
// case when only one wallet is passed in supportedWallets
if (walletConfig && !walletConfig.connectUI) {
onChooseWallet(walletConfig);
if (walletConfig) {
if (walletConfig.connectUI) {
// if there's a connection UI, then show it
setActiveWallet(walletConfig);
} else {
// if there's no connection UI, then connect the wallet
onChooseWallet(walletConfig);
}
}
}, [onChooseWallet, walletConfig]);
@@ -127,7 +137,7 @@ export const ConnectWalletFlow = () => {
subHeaderText=""
content={
activeWallet.id === walletIds.localWallet ? (
<Text variant="bodySmallSecondary" mt="md">
<Text variant="bodySmallSecondary" mt="md" textAlign="center">
Creating, encrypting and securing your device wallet.
</Text>
) : undefined
@@ -142,6 +152,7 @@ export const ConnectWalletFlow = () => {
) : (
<ChooseWallet
headerText={modalTitle}
modalTitleIconUrl={modalTitleIconUrl}
privacyPolicyUrl={privacyPolicyUrl}
termsOfServiceUrl={termsOfServiceUrl}
wallets={supportedWallets}
@@ -1,13 +1,12 @@
import { Icon } from "../../../assets/icon";
import { useAppTheme } from "../../../styles/hooks";
import ImageSvgUri from "../../base/ImageSvgUri";
import Text from "../../base/Text";
import { FlexAlignType, StyleSheet, View } from "react-native";
interface ConnectWalletHeaderProps {
onClose: () => void;
onBackPress?: () => void;
walletLogoUrl?: string;
middleContent?: React.ReactNode;
headerText?: string;
subHeaderText?: string;
alignHeader?: FlexAlignType;
@@ -17,7 +16,7 @@ export const ConnectWalletHeader = ({
headerText,
subHeaderText = "Connecting your wallet",
alignHeader = "center",
walletLogoUrl,
middleContent,
onClose,
onBackPress,
}: ConnectWalletHeaderProps) => {
@@ -33,10 +32,10 @@ export const ConnectWalletHeader = ({
onPress={onBackPress}
color={theme.colors.iconPrimary}
/>
) : null}
{walletLogoUrl ? (
<ImageSvgUri width={56} height={56} imageUrl={walletLogoUrl} />
) : null}
) : (
<View />
)}
{middleContent ? middleContent : null}
<Icon
type="close"
width={14}
@@ -12,6 +12,7 @@ import {
} from "@thirdweb-dev/react-core";
import { LocalWalletImportModal } from "./LocalWalletImportModal";
import { LocalWallet } from "../../wallets/wallets/LocalWallet";
import Box from "../base/Box";
type LocalWalletFlowUIProps = ConnectUIProps<LocalWallet> & {
onConnected?: (wallet: WalletInstance) => void;
@@ -78,9 +79,19 @@ export function LocalWalletFlow({
</Text>
)}
</BaseButton>
<Text variant="subHeader" mt="lg">
-------- OR --------
</Text>
<Box
mt="lg"
marginHorizontal="xl"
flexDirection="row"
justifyContent="center"
alignItems="center"
>
<Box height={1} flex={1} backgroundColor="border" />
<Text variant="subHeader" textAlign="center">
OR
</Text>
<Box height={1} flex={1} backgroundColor="border" />
</Box>
<ModalFooter footer={"Import a wallet"} onPress={onImportPress} />
</View>
@@ -164,10 +164,10 @@ export const LocalWalletImportModal = ({
borderRadius="md"
p="lg"
>
<ModalHeaderTextClose headerText={""} onClose={onCloseInternal} />
<Text variant="header" textAlign="center">
Import JSON Wallet
</Text>
<ModalHeaderTextClose
headerText={"Import JSON Wallet"}
onClose={onCloseInternal}
/>
<Text variant="subHeader" mt="md" textAlign="center">
{
"The application can authorize any transactions on behalf of the wallet without any approvals. We recommend only connecting to trusted applications."
@@ -192,9 +192,18 @@ export const LocalWalletImportModal = ({
<Text variant="bodySmall" color="red" mt="xs" textAlign="left">
{error}
</Text>
<Text variant="bodySmall" m="xs" textAlign="center">
---- Or Private key or Mnemonic ----
</Text>
<Box
mb="xs"
flexDirection="row"
justifyContent="center"
alignItems="center"
>
<Box height={1} flex={1} backgroundColor="border" />
<Text variant="bodySmall" textAlign="center" marginHorizontal="xxs">
Or Private key or Mnemonic
</Text>
<Box height={1} flex={1} backgroundColor="border" />
</Box>
<TextInput
textInputProps={{
secureTextEntry: true,
@@ -202,6 +211,7 @@ export const LocalWalletImportModal = ({
placeholderTextColor: theme.colors.textSecondary,
onChangeText: onPrivateKeyEntered,
}}
containerProps={{ pl: "xxs" }}
/>
<Box
flexDirection="row"
@@ -7,7 +7,7 @@ import {
useCreateWalletInstance,
useWalletContext,
} from "@thirdweb-dev/react-core";
import { StyleSheet, View } from "react-native";
import { ActivityIndicator, StyleSheet, View } from "react-native";
import BaseButton from "../../base/BaseButton";
import Text from "../../base/Text";
import { SmartWallet } from "@thirdweb-dev/wallets";
@@ -15,17 +15,22 @@ import WalletLoadingThumbnail from "../../../wallets/wallets/wallet-connect/Wall
import ImageSvgUri from "../../base/ImageSvgUri";
import Box from "../../base/Box";
import { ConnectWalletHeader } from "../ConnectingWallet/ConnectingWalletHeader";
import { useAppTheme } from "../../../styles/hooks";
export const SmartWalletFlow = ({
close,
goBack,
walletConfig,
}: ConnectUIProps<SmartWallet>) => {
personalWalletConfig,
...props
}: ConnectUIProps<SmartWallet> & { personalWalletConfig: WalletConfig }) => {
const theme = useAppTheme();
const [connectedPersonalWallet, setConnectedPersonalWallet] =
useState<WalletInstance>();
const [personalWalletChainId, setPersonalWalletChaindId] = useState<
number | undefined
>();
const [switchingNetwork, setSwitchingNetwork] = useState(false);
const createWalletInstance = useCreateWalletInstance();
const connect = useConnect();
const targetChain = useWalletContext().activeChain;
@@ -34,6 +39,8 @@ export const SmartWalletFlow = ({
? personalWalletChainId !== targetChain.chainId
: false;
const PersonalWalletConfigUI = personalWalletConfig.connectUI;
const connectSmartWallet = useCallback(
async (personalWallet: WalletInstance) => {
const eoaWalletChainId = await personalWallet.getChainId();
@@ -63,10 +70,14 @@ export const SmartWalletFlow = ({
);
useEffect(() => {
if (walletConfig.personalWallets?.[0]) {
if (walletConfig.personalWallets?.[0] && !PersonalWalletConfigUI) {
connectPersonalWallet(walletConfig.personalWallets[0]);
}
}, [connectPersonalWallet, walletConfig.personalWallets]);
}, [
PersonalWalletConfigUI,
connectPersonalWallet,
walletConfig.personalWallets,
]);
const onConnectingClosePress = () => {
connectedPersonalWallet?.disconnect();
@@ -81,8 +92,13 @@ export const SmartWalletFlow = ({
};
const onSwitchNetworkPress = async () => {
await connectedPersonalWallet?.switchChain(targetChain.chainId);
setPersonalWalletChaindId(targetChain.chainId);
if (connectedPersonalWallet) {
setSwitchingNetwork(true);
await connectedPersonalWallet?.switchChain(targetChain.chainId);
setSwitchingNetwork(false);
setPersonalWalletChaindId(targetChain.chainId);
connectSmartWallet(connectedPersonalWallet);
}
};
const reset = () => {
@@ -90,38 +106,54 @@ export const SmartWalletFlow = ({
setPersonalWalletChaindId(undefined);
};
const onPersonalWalletConnected = useCallback(
(walletInstance: WalletInstance) => {
setConnectedPersonalWallet(walletInstance);
connectSmartWallet(walletInstance);
},
[connectSmartWallet],
);
return (
<>
<Box paddingHorizontal="xl">
<ConnectWalletHeader
subHeaderText=""
onBackPress={onConnectingBackPress}
onClose={onConnectingClosePress}
{PersonalWalletConfigUI && !connectedPersonalWallet ? (
<PersonalWalletConfigUI
{...props}
close={close}
goBack={goBack}
walletConfig={personalWalletConfig}
onLocallyConnected={onPersonalWalletConnected}
/>
<WalletLoadingThumbnail imageSize={100}>
<ImageSvgUri
height={80}
width={80}
imageUrl={walletConfig.meta.iconURL}
) : (
<Box paddingHorizontal="xl">
<ConnectWalletHeader
subHeaderText=""
onBackPress={onConnectingBackPress}
onClose={onConnectingClosePress}
/>
</WalletLoadingThumbnail>
<View style={styles.connectingContainer}>
<>
<Text variant="header" mt="lg">
{mismatch
? "Network Mismatch"
: `Connecting ${walletConfig.meta.name}`}
</Text>
{mismatch ? (
<Text variant="bodySmallSecondary" mt="lg" textAlign="center">
{
"There's a network mismatch between your contract and your wallet"
}
<WalletLoadingThumbnail imageSize={100}>
<ImageSvgUri
height={80}
width={80}
imageUrl={walletConfig.meta.iconURL}
/>
</WalletLoadingThumbnail>
<View style={styles.connectingContainer}>
<>
<Text variant="header" mt="lg" textAlign="center">
{mismatch ? "Network Mismatch" : "Connecting..."}
</Text>
) : null}
</>
</View>
</Box>
{mismatch ? (
<Text variant="bodySmallSecondary" mt="lg" textAlign="center">
{
"There's a network mismatch between your contract and your wallet"
}
</Text>
) : null}
</>
</View>
</Box>
)}
{mismatch === true ? (
<BaseButton
@@ -129,7 +161,7 @@ export const SmartWalletFlow = ({
mt="md"
marginHorizontal="xl"
flexDirection="row"
justifyContent="flex-start"
justifyContent="center"
alignItems="center"
paddingHorizontal="md"
paddingVertical="sm"
@@ -137,9 +169,13 @@ export const SmartWalletFlow = ({
backgroundColor="backgroundHighlight"
onPress={onSwitchNetworkPress}
>
<Text variant="bodyLarge" textAlign="center">
Switch Network
</Text>
{switchingNetwork ? (
<ActivityIndicator size="small" color={theme.colors.textPrimary} />
) : (
<Text variant="bodyLarge" textAlign="center">
Switch Network
</Text>
)}
</BaseButton>
) : null}
</>
@@ -2,18 +2,19 @@ import { useModalState } from "../providers/ui-context-provider";
import { ConnectWalletFlow } from "./ConnectWalletFlow/ConnectWalletFlow";
import { Dimensions, StyleSheet, View } from "react-native";
import { useMemo } from "react";
import { CLOSE_MODAL_STATE } from "../utils/modalTypes";
import { ThemeProvider } from "../styles/ThemeProvider";
import { SessionRequestModal } from "./ConnectWalletDetails/SessionRequestModal";
import { SessionProposalModal } from "./ConnectWalletDetails/SessionProposalModal";
import { TWModal } from "./base/modal/TWModal";
import Box from "./base/Box";
import { useAppTheme } from "../styles/hooks";
const MODAL_HEIGHT = Dimensions.get("window").height * 0.6;
const DEVICE_WIDTH = Dimensions.get("window").width;
export const MainModal = () => {
const { modalState, setModalState } = useModalState();
const theme = useAppTheme();
const { modalState } = useModalState();
const { isOpen, isSheet } = modalState;
@@ -32,13 +33,9 @@ export const MainModal = () => {
}
}, [modalState.view]);
const onBackdropPress = () => {
setModalState(CLOSE_MODAL_STATE("MainModal"));
};
return (
<ThemeProvider>
<TWModal isVisible={isOpen} onBackdropPress={onBackdropPress}>
<ThemeProvider theme={theme}>
<TWModal isVisible={isOpen}>
{isSheet ? (
<Box backgroundColor="background" style={styles.modal}>
<View style={styles.contentContainer}>{view}</View>
@@ -25,6 +25,7 @@ export const PasswordInput = ({
borderWidth={1}
borderRadius="md"
pr="xs"
pl="xxs"
>
<TextInput
style={{ ...styles.textInput, color: theme.colors.textPrimary }}
@@ -62,6 +63,5 @@ const styles = StyleSheet.create({
textAlign: "left",
flex: 1,
height: 40,
paddingLeft: 5,
},
});
@@ -16,13 +16,6 @@ import DownloadIcon from "../assets/download";
import CopyIcon from "../assets/copy";
import QRCode from "react-native-qrcode-svg";
// type SendButtonProps = {
// chain?: Chain;
// onPress?: () => void;
// switchChainOnPress?: boolean;
// onChainSwitched?: () => void;
// };
export const ReceiveButton = () => {
const theme = useAppTheme();
const [isModalVisible, setIsModalVisible] = useState(false);
@@ -100,7 +93,7 @@ export const ReceiveFundsModal = ({
p="lg"
>
<ModalHeaderTextClose
onBackPress={onCloseInternal}
onClose={onCloseInternal}
headerText="Receive Funds"
/>
<Text
@@ -109,11 +102,11 @@ export const ReceiveFundsModal = ({
mt="md"
marginHorizontal="xmd"
>
Paste the wallet address or scan the QR code to send funds to this
Copy the wallet address or scan the QR code to send funds to this
wallet.
</Text>
<Text mt="lg" variant="bodySmallSecondary">
Current Network
Your address
</Text>
<BaseButton
mt="xs"
@@ -126,7 +119,11 @@ export const ReceiveFundsModal = ({
onPress={onAddressPress}
p="md"
>
<AddressDisplay address={address} variant="bodySmall" />
<AddressDisplay
address={address}
variant="bodySmall"
extraShort={false}
/>
<CopyIcon width={14} height={14} color={theme.colors.iconPrimary} />
</BaseButton>
<Text mt="lg" variant="bodySmallSecondary">
@@ -16,14 +16,14 @@ export function SelectTokenButton(props: {
flexDirection="row"
alignItems="center"
onPress={props.onPress}
mb="md"
mb="sm"
>
{props.token?.icon ? (
<ImageSvgUri width={32} height={32} imageUrl={props.token.icon} />
) : (
<ChainIcon chainIconUrl={chain?.icon?.url} size={32} active={false} />
<ChainIcon chainIconUrl={chain?.icon?.url} size={32} />
)}
<Box ml="md" alignItems="flex-start" justifyContent="center" height={36}>
<Box ml="md" alignItems="flex-start" justifyContent="center">
<Text variant="bodyLarge">{tokenName}</Text>
{!balanceQuery.data ? (
<LoadingTextAnimation
@@ -24,7 +24,7 @@ import {
useChainId,
useWallet,
} from "@thirdweb-dev/react-core";
import { SupportedTokens, TokenInfo } from "./defaultTokens";
import { SupportedTokens, TokenInfo, defaultTokens } from "./defaultTokens";
import { useMutation } from "@tanstack/react-query";
import { utils } from "ethers";
import LoadingTextAnimation from "../base/LoadingTextAnimation";
@@ -82,9 +82,24 @@ export const SendFundsModal = ({
onClose,
supportedTokens,
}: SendFundsModalProps) => {
const [token, setToken] = useState<TokenInfo | undefined>();
const [showTokenSelector, setShowTokenSelector] = useState(false);
const chainId = useChainId();
let defaultToken: TokenInfo | undefined = undefined;
if (
// if we know chainId
chainId &&
// if there is a list of tokens for this chain
supportedTokens[chainId] &&
// if the list of tokens is not the default list
supportedTokens[chainId] !== defaultTokens[chainId]
) {
// use the first token in the list as default selected
defaultToken = supportedTokens[chainId][0];
}
const [token, setToken] = useState<TokenInfo | undefined>(defaultToken);
const onTokenSelectorPress = () => {
setShowTokenSelector(true);
};
@@ -204,10 +219,7 @@ const SendFundsForm = ({
borderRadius="md"
p="lg"
>
<ModalHeaderTextClose
onBackPress={onCloseInternal}
headerText="Send Funds"
/>
<ModalHeaderTextClose onClose={onCloseInternal} headerText="Send Funds" />
<Text mt="lg" variant="bodySmallSecondary">
Select Token
</Text>
@@ -228,11 +240,7 @@ const SendFundsForm = ({
{token?.icon ? (
<ImageSvgUri width={32} height={32} imageUrl={token.icon} />
) : (
<ChainIcon
chainIconUrl={chain?.icon?.url}
size={32}
active={false}
/>
<ChainIcon chainIconUrl={chain?.icon?.url} size={32} />
)}
<Box
ml="md"
@@ -1,17 +1,28 @@
import { StyleSheet, View } from "react-native";
export const ActiveDot = () => {
return <View style={styles.dot} />;
export const ActiveDot = ({
width = 28,
height = 28,
color,
}: {
width?: number;
height?: number;
color?: string;
}) => {
return (
<View
style={{
...styles.dot,
backgroundColor: color ? color : "#00d395",
width: width,
height: height,
}}
/>
);
};
const styles = StyleSheet.create({
dot: {
width: 28,
height: 28,
borderRadius: 50,
top: "60%",
right: 0,
backgroundColor: "#00d395",
position: "absolute",
},
});
@@ -1,4 +1,3 @@
import { ActiveDot } from "./ActiveDot";
import ImageSvgUri from "./ImageSvgUri";
import { StyleSheet, View } from "react-native";
@@ -8,16 +7,14 @@ const defaultChainIcon =
export type ChainIconProps = {
chainIconUrl?: string;
size: number;
active?: boolean;
};
export const ChainIcon = ({ chainIconUrl, size, active }: ChainIconProps) => {
export const ChainIcon = ({ chainIconUrl, size }: ChainIconProps) => {
const src = chainIconUrl || defaultChainIcon;
return (
<View style={styles.container}>
<ImageSvgUri width={size} height={size} imageUrl={src} />
{active ? <ActiveDot /> : null}
</View>
);
};
@@ -37,14 +37,7 @@ const ImageSvgUri = ({
return (
<Box style={{ width: width, height: height }}>
{error ? (
<SvgUri
width={width}
height={height}
uri={resolvedImageUrl}
onError={(err) => {
console.warn("Error loading an svg image: ", err);
}}
/>
<SvgUri width={width} height={height} uri={resolvedImageUrl} />
) : (
// always try to render Image first, if error then try to render svg
// Image from RN handles onError better than SvgUri
@@ -72,7 +72,7 @@ export const NetworkButton = ({
<>
<BaseButton
p={padding || "sm"}
borderRadius="xs"
borderRadius="md"
borderWidth={0.5}
flexDirection="row"
alignItems="center"
@@ -82,7 +82,7 @@ export const NetworkButton = ({
{...props}
>
<Box flexDirection="row" alignItems="center">
<ChainIcon chainIconUrl={chain?.icon?.url} size={32} active={false} />
<ChainIcon chainIconUrl={chain?.icon?.url} size={32} />
<Box
ml="md"
alignItems="flex-start"
@@ -1,15 +1,21 @@
import { StyleSheet, TextInput as TextInputRN } from "react-native";
import Box from "./Box";
import { useTheme } from "@shopify/restyle";
import { ReactNode } from "react";
type TextInputProps = {
containerProps?: (typeof Box)["arguments"];
textInputProps?: TextInputRN["props"];
} & {
rightElement?: ReactNode;
leftElement?: ReactNode;
};
export const TextInput = ({
containerProps,
textInputProps,
rightElement,
leftElement,
}: TextInputProps) => {
const theme = useTheme();
@@ -23,6 +29,7 @@ export const TextInput = ({
pr="xs"
{...containerProps}
>
{leftElement ? leftElement : null}
<TextInputRN
style={{ ...styles.textInput, color: theme.colors.textPrimary }}
returnKeyType={"done"}
@@ -31,6 +38,7 @@ export const TextInput = ({
autoCorrect={false}
{...textInputProps}
/>
{rightElement ? rightElement : null}
</Box>
);
};
@@ -6,7 +6,7 @@ import Text from "./Text";
import Box from "./Box";
type WalletButtonProps = {
onPress: () => void;
onPress?: () => void;
walletIconUrl: string;
name: string;
labelText?: string;
@@ -20,6 +20,7 @@ export const WalletButton = ({
name,
labelText,
recommended,
...props
}: WalletButtonProps) => {
return (
<BaseButton
@@ -32,6 +33,7 @@ export const WalletButton = ({
borderRadius="sm"
backgroundColor="background"
onPress={onPress}
{...props}
>
<Box flexDirection="row" justifyContent="flex-start" alignItems="center">
<ImageSvgUri imageUrl={walletIconUrl} width={48} height={48} />
@@ -1,5 +1,7 @@
import Modal, { ModalProps } from "react-native-modal";
const MAX_WIDTH = 500;
// Populate with the data...
export function TWModal(props: Partial<ModalProps>) {
return (
@@ -8,6 +10,7 @@ export function TWModal(props: Partial<ModalProps>) {
avoidKeyboard
useNativeDriver
hideModalContentWhileAnimating={true}
style={{ maxWidth: MAX_WIDTH }}
>
{props.children}
</Modal>
+3
View File
@@ -19,6 +19,8 @@ export { magicWallet } from "./wallets/wallets/magic-link";
export { MagicWallet } from "./wallets/wallets/MagicLink";
export { MagicLink } from "./wallets/wallets/MagicLink";
export { magicLink } from "./wallets/wallets/magic-link";
export { EmbeddedWallet } from "./wallets/wallets/embedded/EmbeddedWallet";
export { embeddedWallet } from "./wallets/wallets/embedded/embedded-wallet";
export * from "./wallets/wallets/wallet-connect/WalletConnectBase";
export { WalletConnect } from "./wallets/wallets/wallet-connect/WalletConnect";
export { walletConnect } from "./wallets/wallets/wallet-connect/wallet-connect";
@@ -42,6 +44,7 @@ export { ThirdwebStorage } from "../core/storage/storage";
// ui components
export * from "./components/base";
export { ConnectWalletHeader } from "./components/ConnectWalletFlow/ConnectingWallet/ConnectingWalletHeader";
// assets / icons
export * from "./assets";
@@ -40,8 +40,8 @@ export const paletteBase = {
};
export const paletteLight: Palette = {
buttonBackgroundColor: "white",
buttonTextColor: "black",
buttonBackgroundColor: "black",
buttonTextColor: "white",
accentButtonColor: "#3385FF",
accentButtonTextColor: "white",
@@ -66,8 +66,8 @@ export const paletteLight: Palette = {
};
export const paletteDark: Palette = {
buttonBackgroundColor: "black",
buttonTextColor: "white",
buttonBackgroundColor: "white",
buttonTextColor: "black",
accentButtonColor: "#3385FF",
accentButtonTextColor: "white",
@@ -0,0 +1 @@
declare module "react-native-aes-gcm-crypto";
@@ -52,6 +52,7 @@ export type ClosedModal = {
// connect wallet flow
export type ConnectWalletFlowData = {
modalTitle?: string;
modalTitleIconUrl?: string;
termsOfServiceUrl?: string;
privacyPolicyUrl?: string;
walletConfig?: WalletConfig;
@@ -0,0 +1,212 @@
import {
EmbeddedWalletConnectionArgs,
EmbeddedWalletConnectorOptions,
} from "./types";
import type { Chain } from "@thirdweb-dev/chains";
import { Connector, normalizeChainId } from "@thirdweb-dev/wallets";
import { providers, Signer } from "ethers";
import { utils } from "ethers";
import { sendEmailOTP, validateEmailOTP } from "./embedded/auth";
import { getEthersSigner } from "./embedded/signer";
import { logoutUser } from "./embedded/helpers/auth/logout";
import {
clearConnectedEmail,
getConnectedEmail,
saveConnectedEmail,
} from "./embedded/helpers/storage/local";
export class EmbeddedWalletConnector extends Connector<EmbeddedWalletConnectionArgs> {
private options: EmbeddedWalletConnectorOptions;
signer?: Signer;
email?: string;
constructor(options: EmbeddedWalletConnectorOptions) {
super();
this.options = options;
this.email = getConnectedEmail();
}
async connect(options?: { email?: string; chainId?: number }) {
const connected = await this.isConnected();
if (!connected) {
throw new Error("Not connected");
}
if (options?.chainId) {
this.switchChain(options.chainId);
}
this.setupListeners();
return this.getAddress();
}
async validateEmailOtp(otp: string) {
if (!this.email) {
throw new Error("Email is required to connect");
}
try {
await validateEmailOTP({
clientId: this.options.clientId,
otp,
});
} catch (error) {
console.error(`Error while validating otp: ${error}`);
if (error instanceof Error) {
return { error: error.message };
} else {
return { error: "An unknown error occurred" };
}
}
try {
await this.getSigner();
this.emit("connected");
} catch (error) {
if (error instanceof Error) {
return { error: error.message };
} else {
return { error: "Error getting the signer" };
}
}
return { success: true };
}
async sendEmailOtp(email: string) {
this.email = email;
saveConnectedEmail(email);
return sendEmailOTP(email, this.options.clientId);
}
async disconnect(): Promise<void> {
clearConnectedEmail();
await logoutUser(this.options.clientId);
await this.onDisconnect();
this.signer = undefined;
}
async getAddress(): Promise<string> {
const signer = await this.getSigner();
return signer.getAddress();
}
async isConnected(): Promise<boolean> {
try {
const addr = await this.getAddress();
return !!addr;
} catch (e) {
return false;
}
}
async getProvider(): Promise<providers.Provider> {
const signer = await this.getSigner();
if (!signer.provider) {
throw new Error("Provider not found");
}
return signer.provider;
}
public async getSigner(): Promise<Signer> {
if (this.signer) {
return this.signer;
}
let signer;
try {
signer = await getEthersSigner(this.options.clientId);
} catch (error) {
console.error(`Error while getting the signer: ${error}`);
}
if (!signer) {
throw new Error("Error fetching the signer");
}
this.signer = signer;
if (this.options.chain.chainId) {
this.signer = this.signer.connect(
new providers.JsonRpcProvider(this.options.chain.rpc[0]),
);
}
return signer;
}
async isAuthorized(): Promise<boolean> {
return this.isConnected();
}
async switchChain(chainId: number): Promise<void> {
const chain = this.options.chains.find((c) => c.chainId === chainId);
if (!chain) {
throw new Error("Chain not configured");
}
// update signer
this.signer = await getEthersSigner(this.options.clientId);
this.signer = this.signer.connect(
new providers.JsonRpcProvider(chain.rpc[0]),
);
this.emit("change", { chain: { id: chainId, unsupported: false } });
}
async setupListeners() {
const provider = await this.getProvider();
if (provider.on) {
provider.on("accountsChanged", this.onAccountsChanged);
provider.on("chainChanged", this.onChainChanged);
provider.on("disconnect", this.onDisconnect);
}
}
async removeListeners() {
if (!this.signer) {
return;
}
const provider = await this.getProvider();
if (provider.off) {
provider.off("accountsChanged", this.onAccountsChanged);
provider.off("chainChanged", this.onChainChanged);
provider.off("disconnect", this.onDisconnect);
}
}
updateChains(chains: Chain[]) {
this.options.chains = chains;
}
protected onAccountsChanged = async (accounts: string[]) => {
if (accounts.length === 0) {
await this.onDisconnect();
} else {
this.emit("change", {
account: utils.getAddress(accounts[0] as string),
});
}
};
protected onChainChanged = (chainId: number | string) => {
const id = normalizeChainId(chainId);
const unsupported =
this.options.chains.findIndex((c) => c.chainId === id) === -1;
this.emit("change", { chain: { id, unsupported } });
};
protected onDisconnect = async () => {
this.removeListeners();
this.emit("disconnect");
};
getEmail() {
return this.email;
}
}
@@ -0,0 +1,124 @@
import {
AuthProvider,
AuthStoredTokenWithCookieReturnType,
RecoveryShareManagement,
} from "@paperxyz/embedded-wallet-service-sdk";
import type { CognitoUser } from "amazon-cognito-identity-js";
import { Auth } from "aws-amplify";
import {
generateAuthTokenFromCognitoEmailOtp,
getEmbeddedWalletUserDetail,
verifyClientId,
} from "./helpers/api/fetchers";
import {
cognitoEmailSignIn,
cognitoEmailSignUp,
} from "./helpers/auth/cognitoAuth";
import { postPaperAuth, prePaperAuth } from "./helpers/auth/middleware";
import { isDeviceSharePresentForUser } from "./helpers/storage/local";
import { getCognitoUser, setCognitoUser } from "./helpers/storage/state";
import { SendEmailOtpReturnType } from "@thirdweb-dev/wallets";
export async function sendEmailOTP(
email: string,
clientId: string,
): Promise<SendEmailOtpReturnType> {
await verifyClientId(clientId);
await prePaperAuth({
authenticationMethod: AuthProvider.COGNITO,
email,
});
// AWS Auth flow
let cognitoUser: CognitoUser;
try {
cognitoUser = await cognitoEmailSignIn(email, clientId);
} catch (e) {
await cognitoEmailSignUp(email, clientId);
cognitoUser = await cognitoEmailSignIn(email, clientId);
}
setCognitoUser(cognitoUser);
let result: Awaited<ReturnType<typeof getEmbeddedWalletUserDetail>>;
try {
result = await getEmbeddedWalletUserDetail({
email,
clientId,
});
} catch (e) {
throw new Error(
`Malformed response from the send email OTP API: ${JSON.stringify(e)}`,
);
}
return result.isNewUser
? {
isNewUser: result.isNewUser,
isNewDevice: true,
recoveryShareManagement: RecoveryShareManagement.AWS_MANAGED,
}
: {
isNewUser: result.isNewUser,
isNewDevice: !(await isDeviceSharePresentForUser(
clientId,
result.walletUserId ?? "",
)),
recoveryShareManagement: RecoveryShareManagement.AWS_MANAGED,
};
}
export async function validateEmailOTP({
clientId,
otp,
}: {
otp: string;
clientId: string;
}): Promise<AuthStoredTokenWithCookieReturnType> {
let verifiedToken: Awaited<
ReturnType<typeof generateAuthTokenFromCognitoEmailOtp>
>["verifiedToken"];
let verifiedTokenJwtString: string;
try {
let cognitoUser = getCognitoUser();
if (!cognitoUser) {
throw new Error("MISSING COGNITO USER");
}
cognitoUser = await Auth.sendCustomChallengeAnswer(cognitoUser, otp);
// It we get here, the answer was sent successfully,
// but it might have been wrong (1st or 2nd time)
// So we should test if the user is authenticated now
const session = await Auth.currentSession();
({ verifiedToken, verifiedTokenJwtString } =
await generateAuthTokenFromCognitoEmailOtp(session, clientId));
} catch (e) {
throw new Error(`Invalid OTP ${e}`);
}
try {
const storedToken: AuthStoredTokenWithCookieReturnType["storedToken"] = {
jwtToken: verifiedToken.rawToken,
authDetails: verifiedToken.authDetails,
authProvider: verifiedToken.authProvider,
developerClientId: verifiedToken.developerClientId,
cookieString: verifiedTokenJwtString,
// we should always store the jwt cookie since there's no concept of cookie in react native
shouldStoreCookieString: true,
isNewUser: verifiedToken.isNewUser,
};
await postPaperAuth(storedToken, clientId);
return { storedToken };
} catch (e) {
throw new Error(
`Malformed response from the verify one time password: ${JSON.stringify(
e,
)}`,
);
}
}
@@ -0,0 +1,243 @@
import {
AuthProvider,
RecoveryShareManagement,
} from "@paperxyz/embedded-wallet-service-sdk";
import { CognitoUserSession } from "amazon-cognito-identity-js";
import {
ROUTE_GET_EMBEDDED_WALLET_DETAILS,
ROUTE_INIT_RECOVERY_CODE_FREE_WALLET,
ROUTE_STORE_USER_SHARES,
ROUTE_VERIFY_THIRDWEB_CLIENT_ID,
ROUTE_VERIFY_COGNITO_OTP,
} from "../constants";
import { getAuthTokenClient } from "../storage/local";
import * as Application from "expo-application";
const EMBEDDED_WALLET_TOKEN_HEADER = "embedded-wallet-token";
const PAPER_CLIENT_ID_HEADER = "x-paper-client-id";
const BUNDLE_ID_HEADER = "x-bundle-id";
const APP_BUNDLE_ID = Application.applicationId || "";
export const verifyClientId = async (clientId: string) => {
const resp = await fetch(ROUTE_VERIFY_THIRDWEB_CLIENT_ID, {
method: "POST",
headers: {
"Content-Type": "application/json",
[BUNDLE_ID_HEADER]: APP_BUNDLE_ID,
},
body: JSON.stringify({ clientId, parentDomain: "" }),
});
if (!resp.ok) {
const { error } = await resp.json();
throw new Error(
`Something went wrong generating auth token from user cognito email otp. ${error}`,
);
}
return {
success: true,
};
};
export const authFetchEmbeddedWalletUser = async (
{ clientId }: { clientId: string },
url: Parameters<typeof fetch>[0],
props: Parameters<typeof fetch>[1],
): Promise<Response> => {
const authTokenClient = await getAuthTokenClient(clientId);
const params = { ...props };
params.headers = params?.headers
? {
...params.headers,
Authorization: `Bearer ${EMBEDDED_WALLET_TOKEN_HEADER}:${
authTokenClient || ""
}`,
[BUNDLE_ID_HEADER]: APP_BUNDLE_ID,
[PAPER_CLIENT_ID_HEADER]: clientId,
}
: {
Authorization: `Bearer ${EMBEDDED_WALLET_TOKEN_HEADER}:${
authTokenClient || ""
}`,
[BUNDLE_ID_HEADER]: APP_BUNDLE_ID,
[PAPER_CLIENT_ID_HEADER]: clientId,
};
return fetch(url, params);
};
export async function getEmbeddedWalletUserDetail(args: {
email?: string;
userWalletId?: string;
clientId: string;
}) {
const url = new URL(ROUTE_GET_EMBEDDED_WALLET_DETAILS);
if (args) {
if (args.email) {
url.searchParams.append("email", args.email);
}
if (args.userWalletId) {
url.searchParams.append("userWalletId", args.userWalletId);
}
url.searchParams.append("clientId", args.clientId);
}
const resp = await authFetchEmbeddedWalletUser(
{ clientId: args.clientId },
url.href,
{
method: "GET",
},
);
if (!resp.ok) {
const { error } = await resp.json();
throw new Error(`Something went wrong determining wallet type. ${error}`);
}
const result = (await resp.json()) as
| {
isNewUser: true;
}
| {
isNewUser: false;
walletUserId: string;
recoveryShareManagement: RecoveryShareManagement;
};
return result;
}
export async function generateAuthTokenFromCognitoEmailOtp(
session: CognitoUserSession,
clientId: string,
) {
const resp = await fetch(ROUTE_VERIFY_COGNITO_OTP, {
method: "POST",
headers: {
"Content-Type": "application/json",
[BUNDLE_ID_HEADER]: APP_BUNDLE_ID,
},
body: JSON.stringify({
access_token: session.getAccessToken().getJwtToken(),
refresh_token: session.getRefreshToken().getToken(),
id_token: session.getIdToken().getJwtToken(),
developerClientId: clientId,
otpMethod: "email",
recoveryShareManagement: RecoveryShareManagement.AWS_MANAGED,
}),
});
if (!resp.ok) {
const { error } = await resp.json();
throw new Error(
`Something went wrong generating auth token from user cognito email otp. ${error}`,
);
}
const respJ = await resp.json();
return respJ as {
verifiedToken: {
rawToken: string;
authDetails: {
email?: string;
userWalletId: string;
recoveryCode?: string;
recoveryShareManagement: RecoveryShareManagement;
};
authProvider: AuthProvider;
userId: string;
developerClientId: string;
isNewUser: boolean;
};
verifiedTokenJwtString: string;
};
}
export async function initWalletWithoutRecoveryCode({
clientId,
}: {
clientId: string;
}) {
const resp = await authFetchEmbeddedWalletUser(
{ clientId },
ROUTE_INIT_RECOVERY_CODE_FREE_WALLET,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
clientId,
}),
},
);
if (!resp.ok) {
const { error } = await resp.json();
console.error(`Error initializing wallet: ${error} `);
return { success: false };
}
return { success: true };
}
export async function storeUserShares({
clientId,
walletAddress,
maybeEncryptedRecoveryShares,
authShare,
}: {
clientId: string;
walletAddress: string;
maybeEncryptedRecoveryShares?: {
share: string;
isClientEncrypted: boolean;
}[];
authShare?: string;
}) {
const resp = await authFetchEmbeddedWalletUser(
{ clientId },
ROUTE_STORE_USER_SHARES,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
walletAddress,
maybeEncryptedRecoveryShares,
authShare,
}),
},
);
if (!resp.ok) {
const { error } = await resp.json();
throw new Error(
`Something went wrong storing user wallet shares: ${JSON.stringify(
error,
null,
2,
)}`,
);
}
}
export async function getUserShares(clientId: string, getShareUrl: URL) {
const resp = await authFetchEmbeddedWalletUser(
{ clientId },
getShareUrl.href,
{
method: "GET",
},
);
if (!resp.ok) {
const { error } = await resp.json();
throw new Error(
`Something went wrong getting user's wallet: ${JSON.stringify(
error,
null,
2,
)} `,
);
}
const respJ = await resp.json();
try {
return respJ as {
authShare?: string;
maybeEncryptedRecoveryShares?: string[];
};
} catch (e) {
throw new Error(
`Malformed response from the ews user wallet API: ${JSON.stringify(e)}`,
);
}
}
@@ -0,0 +1,38 @@
import { Amplify, Auth } from "aws-amplify";
import {
AWS_REGION,
COGNITO_APP_CLIENT_ID,
COGNITO_USER_POOL_ID,
} from "../constants";
import { getRandomValues } from "../getRandomValues";
Amplify.configure({
Auth: {
region: AWS_REGION,
userPoolId: COGNITO_USER_POOL_ID,
userPoolWebClientId: COGNITO_APP_CLIENT_ID,
},
});
export async function cognitoEmailSignUp(email: string, clientId: string) {
await Auth.signUp({
username: `${email}:email:${clientId}`,
password: getRandomString(30),
attributes: {
email,
},
});
await Auth.signOut();
}
function getRandomString(bytes: number) {
const randomValues = getRandomValues(new Uint8Array(bytes));
return Array.from(randomValues)
.map((nr) => nr.toString(16).padStart(2, "0"))
.join("");
}
export async function cognitoEmailSignIn(email: string, clientId: string) {
const cognitoUser = await Auth.signIn(`${email}:email:${clientId}`);
return cognitoUser;
}
@@ -0,0 +1,13 @@
import {
removeAuthTokenInClient,
removeLoggedInWalletUserId,
} from "../storage/local";
import { getCognitoUser } from "../storage/state";
export async function logoutUser(clientId: string): Promise<boolean> {
const isLoggedUserOutIncognito = await removeAuthTokenInClient(clientId);
await removeLoggedInWalletUserId(clientId);
const cognitoUser = getCognitoUser();
cognitoUser?.signOut();
return isLoggedUserOutIncognito;
}
@@ -0,0 +1,63 @@
import {
AuthProvider,
AuthStoredTokenWithCookieReturnType,
} from "@paperxyz/embedded-wallet-service-sdk";
import {
getDeviceShare,
setAuthTokenClient,
setWallerUserDetails,
} from "../storage/local";
import { setUpNewUserWallet } from "../wallet/creation";
import { getCognitoRecoveryPassword } from "../wallet/recoveryCode";
import { setUpShareForNewDevice } from "../wallet/retrieval";
export async function prePaperAuth(args: {
authenticationMethod: AuthProvider;
email: string;
}) {
// TODO: Add tracking here
Promise.resolve(args);
}
export async function postPaperAuth(
storedToken: AuthStoredTokenWithCookieReturnType["storedToken"],
clientId: string,
) {
if (storedToken.shouldStoreCookieString) {
await setAuthTokenClient(storedToken.cookieString, clientId);
}
await setWallerUserDetails({
clientId,
userId: storedToken.authDetails.userWalletId,
email: storedToken.authDetails.email,
});
if (storedToken.isNewUser) {
console.log("========== New User ==========");
const recoveryCode = await getCognitoRecoveryPassword(clientId);
await setUpNewUserWallet(recoveryCode, clientId);
} else {
try {
// existing device share
await getDeviceShare(clientId);
console.log("========== Existing user with device share ==========");
} catch (e) {
// trying to recreate device share from recovery code to derive wallet
const recoveryCode = await getCognitoRecoveryPassword(clientId);
console.log("========== Existing user on new device ==========");
try {
await setUpShareForNewDevice({
clientId,
recoveryCode,
});
} catch (error) {
console.error("Error setting up wallet on device", error);
throw error;
}
}
}
return storedToken;
}
@@ -0,0 +1,33 @@
export const AUTH_SHARE_ID = 3;
export const AUTH_SHARE_INDEX = AUTH_SHARE_ID - 1;
export const NO_EXISTING_WALLET_FOUND_FOR_USER =
"User does not have an existing wallet. Create a wallet first";
export const DEVICE_SHARE_ID = 1;
export const DEVICE_SHARE_INDEX = DEVICE_SHARE_ID - 1;
export const DEVICE_SHARE_MISSING_MESSAGE = "Missing device share.";
export const RECOVERY_SHARE_ID = 2;
export const RECOVERY_SHARE_INDEX = RECOVERY_SHARE_ID - 1;
export const AWS_REGION = "us-west-2";
export const COGNITO_USER_POOL_ID = "us-west-2_UFwLcZIpq";
export const COGNITO_APP_CLIENT_ID = "2e02ha2ce6du13ldk8pai4h3d0";
export const COGNITO_IDENTITY_POOL_ID =
"us-west-2:2ad7ab1e-f48b-48a6-adfa-ac1090689c26";
export const GENERATE_RECOVERY_PASSWORD_LAMBDA_FUNCTION =
"arn:aws:lambda:us-west-2:324457261097:function:recovery-share-password-GenerateRecoverySharePassw-bbE5ZbVAToil";
const BASE_URL = "https://ews.thirdweb.com";
const ROUTE_2022_08_12_API_BASE_PATH = `${BASE_URL}/api/2022-08-12`;
export const ROUTE_GET_EMBEDDED_WALLET_DETAILS = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/user-wallet-details`;
export const ROUTE_VERIFY_COGNITO_OTP = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/verify-cognito-otp`;
export const ROUTE_COGNITO_IDENTITY_POOL_URL = `cognito-idp.${AWS_REGION}.amazonaws.com/${COGNITO_USER_POOL_ID}`;
export const ROUTE_INIT_RECOVERY_CODE_FREE_WALLET = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/init-recovery-code-free-wallet`;
export const ROUTE_STORE_USER_SHARES = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/store-shares`;
export const ROUTE_GET_USER_SHARES = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/get-shares`;
export const ROUTE_VERIFY_THIRDWEB_CLIENT_ID = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/verify-thirdweb-client-id`;
export const ROUTE_AUTH_COGNITO_ID_TOKEN = `${ROUTE_2022_08_12_API_BASE_PATH}/embedded-wallet/cognito-id-token`;
@@ -0,0 +1,13 @@
type IntArrayBufferView =
| Int8Array
| Uint8Array
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array[];
export function getRandomValues<T extends IntArrayBufferView>(array: T): T {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore getRandomValues is polyfilled
return crypto.getRandomValues(array);
}
@@ -0,0 +1,157 @@
import {
AUTH_TOKEN_LOCAL_STORAGE_NAME,
DEVICE_SHARE_LOCAL_STORAGE_NAME,
WALLET_USER_DETAILS_LOCAL_STORAGE_NAME,
WALLET_USER_ID_LOCAL_STORAGE_NAME,
} from "@paperxyz/embedded-wallet-service-sdk";
import { MMKV } from "react-native-mmkv";
import { DEVICE_SHARE_MISSING_MESSAGE } from "../constants";
const CONNECTED_EMAIL_LOCAL_STORAGE_NAME = "embedded-wallet-connected-email";
const storage = new MMKV();
const getItemFromAsyncStorage = (key: string) => {
return storage.getString(key);
};
const setItemInAsyncStorage = async (key: string, value: string) => {
storage.set(key, value);
};
const removeItemInAsyncStorage = async (key: string) => {
storage.delete(key);
};
export function getConnectedEmail() {
return getItemFromAsyncStorage(CONNECTED_EMAIL_LOCAL_STORAGE_NAME);
}
export function saveConnectedEmail(email: string) {
setItemInAsyncStorage(CONNECTED_EMAIL_LOCAL_STORAGE_NAME, email);
}
export function clearConnectedEmail() {
removeItemInAsyncStorage(CONNECTED_EMAIL_LOCAL_STORAGE_NAME);
}
export async function isDeviceSharePresentForUser(
clientId: string,
walletUserId?: string,
): Promise<boolean> {
if (!walletUserId) {
return false;
}
const storedDeviceShare = getItemFromAsyncStorage(
DEVICE_SHARE_LOCAL_STORAGE_NAME(clientId, walletUserId),
);
return !!storedDeviceShare;
}
export async function getAuthTokenClient(clientId: string) {
return getItemFromAsyncStorage(AUTH_TOKEN_LOCAL_STORAGE_NAME(clientId));
}
export async function setAuthTokenClient(
cookieString: string,
clientId: string,
): Promise<void> {
const authToken = AUTH_TOKEN_LOCAL_STORAGE_NAME(clientId);
setItemInAsyncStorage(authToken, cookieString);
}
export async function removeAuthTokenInClient(
clientId: string,
): Promise<boolean> {
const verifiedTokenString = await getAuthTokenClient(clientId);
if (verifiedTokenString) {
await removeItemInAsyncStorage(AUTH_TOKEN_LOCAL_STORAGE_NAME(clientId));
return true;
}
return false;
}
export async function setWallerUserDetails({
clientId,
userId,
email,
}: {
clientId: string;
userId: string;
email?: string;
}) {
const userDetails = await getWalletUserDetails(clientId);
let newEmail = email;
if (userDetails && userDetails.userId === userId && !newEmail) {
newEmail = userDetails.email;
}
const name = WALLET_USER_DETAILS_LOCAL_STORAGE_NAME(clientId);
await setItemInAsyncStorage(
// ! Keep this in sync with getWalletUserDetails function below
name,
JSON.stringify({ userId, email: newEmail }),
);
}
export async function getWalletUserDetails(
clientId: string,
): Promise<{ userId: string; email?: string } | undefined> {
const result = getItemFromAsyncStorage(
WALLET_USER_DETAILS_LOCAL_STORAGE_NAME(clientId),
);
if (!result) {
return undefined;
}
try {
const parsed = JSON.parse(result);
return parsed;
} catch (e) {
return undefined;
}
}
export async function removeLoggedInWalletUserId(clientId: string) {
await removeItemInAsyncStorage(
WALLET_USER_DETAILS_LOCAL_STORAGE_NAME(clientId),
);
await removeItemInAsyncStorage(WALLET_USER_ID_LOCAL_STORAGE_NAME(clientId));
}
export async function setDeviceShare({
clientId,
deviceShare,
}: {
clientId: string;
deviceShare: string;
}): Promise<string> {
const userDetails = await getWalletUserDetails(clientId);
if (!userDetails) {
throw new Error("Missing wallet user ID");
}
const name = DEVICE_SHARE_LOCAL_STORAGE_NAME(clientId, userDetails.userId);
await setWallerUserDetails({ userId: userDetails.userId, clientId });
await setItemInAsyncStorage(name, deviceShare);
return deviceShare;
}
export async function getDeviceShare(clientId: string) {
const cachedWalletUserId = await getWalletUserDetails(clientId);
if (!cachedWalletUserId) {
throw new Error("Missing wallet user ID");
}
const name = DEVICE_SHARE_LOCAL_STORAGE_NAME(
clientId,
cachedWalletUserId.userId,
);
const deviceShareString = getItemFromAsyncStorage(name);
if (!deviceShareString) {
throw new Error(DEVICE_SHARE_MISSING_MESSAGE);
}
const deviceShare = deviceShareString;
return { deviceShare };
}
@@ -0,0 +1,12 @@
import {CognitoUser} from 'amazon-cognito-identity-js';
// TODO: DO we need to swap this out with a proper state management system?
let cognitoUserAtom: CognitoUser | undefined;
export function getCognitoUser() {
return cognitoUserAtom;
}
export function setCognitoUser(newUser: CognitoUser) {
cognitoUserAtom = newUser;
}
@@ -0,0 +1,160 @@
import { SetUpWalletRpcReturnType } from "@paperxyz/embedded-wallet-service-sdk";
import { Wallet, utils } from "ethers";
import * as secrets from "secrets.js-34r7h";
import {
initWalletWithoutRecoveryCode,
storeUserShares,
} from "../api/fetchers";
import { logoutUser } from "../auth/logout";
import {
AUTH_SHARE_INDEX,
DEVICE_SHARE_INDEX,
DEVICE_SHARE_MISSING_MESSAGE,
RECOVERY_SHARE_INDEX,
} from "../constants";
import { setDeviceShare } from "../storage/local";
import { encryptShareWeb } from "./encryption";
export async function setUpNewUserWallet(
recoveryCode: string,
clientId: string,
) {
try {
// We are using a recovery code override, we mark the wallet as initialized so we don't generate another one the next time
const { success } = await initWalletWithoutRecoveryCode({ clientId });
if (!success) {
throw new Error("Error initializing wallet without recovery code");
}
return await createEmbeddedWallet({
clientId,
recoveryCode: recoveryCode,
});
} catch (e) {
// we log user out so they aren't in the weird state where they are logged in but the wallet is not initialized
await logoutUser(clientId);
throw new Error(
`Error creating new ews account. Please try signing in again. Original Error: ${e}`,
);
}
}
// Wallet Creation
async function createEmbeddedWallet({
clientId,
recoveryCode,
}: {
clientId: string;
recoveryCode: string;
}): Promise<
{
recoveryCode: string;
} & SetUpWalletRpcReturnType
> {
const walletDetails = createWalletShares();
const maybeDeviceShare = await storeShares({
clientId,
walletAddress: walletDetails.publicAddress,
authShare: walletDetails.shares[AUTH_SHARE_INDEX],
deviceShare: walletDetails.shares[DEVICE_SHARE_INDEX],
recoveryShares: [
{
share: walletDetails.shares[RECOVERY_SHARE_INDEX],
recoveryCode,
},
],
});
if (!maybeDeviceShare?.deviceShareStored) {
throw new Error(DEVICE_SHARE_MISSING_MESSAGE);
}
return {
walletAddress: walletDetails.publicAddress,
deviceShareStored: maybeDeviceShare?.deviceShareStored,
isIframeStorageEnabled: false,
recoveryCode,
};
}
function createWalletShares(): {
publicAddress: string;
shares: [string, string, string];
} {
// const wallet = ethers.Wallet.createRandom();
const seed = utils.randomBytes(32);
const wallet = new Wallet(seed);
const privateKeyHex = Buffer.from(`thirdweb_${wallet.privateKey}`).toString(
"hex",
);
// Potential source of share corruption through tampering
// https://hackerone.com/reports/1884071
const shares = secrets.share(privateKeyHex, 3, 2);
return {
publicAddress: wallet.address,
shares: [shares[0], shares[1], shares[2]],
};
}
/**
* Store user's wallet shares. Encrypts authShare and recoveryShare as given clientSide as well.
* @param {string} walletAddress the user's wallet address. Note that for each logged in user and clientId, we have a single walletAddress. This will error if we attempt to store shares for user's with an existing wallet different from the walletAddress
* @param {string} authShare the *unencrypted* authShare for the user
* @param {string} recoveryShare the *unencrypted* recovery share for the user
* @throws if another walletAddress already exists
*/
export async function storeShares<R extends string | undefined>({
clientId,
walletAddress,
authShare,
deviceShare,
recoveryShares,
}: {
clientId: string;
walletAddress: string;
authShare?: string;
deviceShare?: string;
recoveryShares?: R extends string
? { share: R; recoveryCode: string }[]
: never;
}): Promise<{ deviceShareStored: string } | undefined> {
let maybeEncryptedRecoveryShares:
| { share: string; isClientEncrypted: boolean }[]
| undefined;
if (recoveryShares && recoveryShares.length) {
maybeEncryptedRecoveryShares = await Promise.all(
recoveryShares.map(async (recoveryShare) => {
return {
share: await encryptShareWeb(
recoveryShare.share,
recoveryShare.recoveryCode,
),
isClientEncrypted: true,
};
}),
);
}
await storeUserShares({
authShare,
clientId,
maybeEncryptedRecoveryShares,
walletAddress,
});
try {
if (deviceShare) {
const deviceShareStored = await setDeviceShare({
deviceShare,
clientId,
});
return { deviceShareStored };
}
} catch (e) {
throw new Error(
`Malformed response from the ews store user share API: ${JSON.stringify(
e,
)}`,
);
}
}
@@ -0,0 +1,79 @@
import AesGcmCrypto from "react-native-aes-gcm-crypto";
import { getRandomValues } from "../getRandomValues";
import QuickCrypto from "react-native-quick-crypto";
const ENCRYPTION_SEPARATOR = ":";
const KEY_ITERATION_COUNT = 5000000;
const KEY_LENGTH = 256;
export async function getEncryptionKey(
pwd: string,
salt: ArrayBuffer,
): Promise<string> {
const key = QuickCrypto.pbkdf2Sync(
pwd,
salt,
KEY_ITERATION_COUNT,
KEY_LENGTH,
"sha256",
);
// this produces a 256 bits length key
// but node by default produces a 32 byte length key
const key32 = key.slice(0, 32);
const base64key = key32.toString("base64");
return base64key;
}
function bufferToBase64(arrayBuffer: ArrayBuffer): string {
return Buffer.from(arrayBuffer).toString("base64");
}
function base64ToBuffer(base64String: string): ArrayBuffer {
return Buffer.from(base64String, "base64");
}
export async function encryptShareWeb(
share: string,
pwd: string,
): Promise<string> {
const salt = getRandomValues(new Uint8Array(16));
const keyBase64 = await getEncryptionKey(pwd, salt);
let encryptedValue;
try {
encryptedValue = await AesGcmCrypto.encrypt(share, false, keyBase64);
} catch (error) {
throw new Error(`Error encrypting share: ${error}`);
}
const returnValue = `${encryptedValue.content}${ENCRYPTION_SEPARATOR}${
encryptedValue.iv
}${ENCRYPTION_SEPARATOR}${bufferToBase64(salt)}${ENCRYPTION_SEPARATOR}${
encryptedValue.tag
}`;
return returnValue;
}
export async function decryptShareWeb(
encryptedShareDetails: string,
pwd: string,
): Promise<string> {
const [encryptedShare, iv, salt, tag] =
encryptedShareDetails.split(ENCRYPTION_SEPARATOR);
const key = await getEncryptionKey(pwd, base64ToBuffer(salt));
const normalizedShare = await AesGcmCrypto.decrypt(
encryptedShare,
key,
iv,
tag,
false,
);
return normalizedShare;
}
@@ -0,0 +1,72 @@
import {InvokeCommand, LambdaClient} from '@aws-sdk/client-lambda';
import {fromCognitoIdentityPool} from '@aws-sdk/credential-providers';
import {authFetchEmbeddedWalletUser} from '../api/fetchers';
import {
AWS_REGION,
COGNITO_IDENTITY_POOL_ID,
GENERATE_RECOVERY_PASSWORD_LAMBDA_FUNCTION,
ROUTE_AUTH_COGNITO_ID_TOKEN,
ROUTE_COGNITO_IDENTITY_POOL_URL,
} from '../constants';
export async function getCognitoRecoveryPassword(clientId: string) {
const idTokenResponse = await authFetchEmbeddedWalletUser(
{clientId},
ROUTE_AUTH_COGNITO_ID_TOKEN,
{
method: 'GET',
},
);
if (!idTokenResponse.ok) {
throw new Error(
`Failed to fetch id token from Cognito: ${JSON.stringify(
await idTokenResponse.json(),
null,
2,
)}`,
);
}
const idTokenResult = await idTokenResponse.json();
const {
data: {id_token: idToken, access_token: accessToken},
} = idTokenResult;
const cognitoIdentity = fromCognitoIdentityPool({
clientConfig: {
region: AWS_REGION,
},
identityPoolId: COGNITO_IDENTITY_POOL_ID,
logins: {
[ROUTE_COGNITO_IDENTITY_POOL_URL]: idToken,
},
});
const credentials = await cognitoIdentity();
// ? Figure out how to potentially route things through API Gateway
const lambdaClient = new LambdaClient({
region: AWS_REGION,
credentials: credentials,
});
const functionName = GENERATE_RECOVERY_PASSWORD_LAMBDA_FUNCTION;
const params = {
FunctionName: functionName,
Payload: Buffer.from(
JSON.stringify({
accessToken,
idToken,
}),
),
};
const data = await lambdaClient.send(new InvokeCommand(params));
if (!data.Payload) {
throw new Error('No payload');
}
const encKeyResult = JSON.parse(Buffer.from(data.Payload).toString('utf-8'));
const result = JSON.parse(encKeyResult.body).recoveryShareEncKey as string;
return result;
}
@@ -0,0 +1,189 @@
import { SetUpWalletRpcReturnType } from "@paperxyz/embedded-wallet-service-sdk";
import { ethers } from "ethers";
import * as secrets from "secrets.js-34r7h";
import { getUserShares } from "../api/fetchers";
import {
DEVICE_SHARE_ID,
DEVICE_SHARE_MISSING_MESSAGE,
ROUTE_GET_USER_SHARES,
} from "../constants";
import { getDeviceShare } from "../storage/local";
import { storeShares } from "./creation";
import { decryptShareWeb } from "./encryption";
function getWalletPrivateKeyFromShares(shares: string[]) {
const privateKeyHex = secrets.combine(shares);
const prefixPrivateKey = Buffer.from(privateKeyHex, "hex").toString("utf-8");
if (!prefixPrivateKey.startsWith("thirdweb_")) {
throw new Error("Invalid private key reconstructed from shares");
}
const privateKey = prefixPrivateKey.replace("thirdweb_", "");
return privateKey;
}
export function getUserEtherJsWalletFromShares(args: {
shares: string[];
}): ethers.Wallet {
const { shares } = args;
return new ethers.Wallet(getWalletPrivateKeyFromShares(shares));
}
/**
* For users on a known device and logged in.
* Will throw if called on a new device // user not logged in
*/
export async function getExistingUserEtherJsWallet(clientId: string) {
const { authShare, deviceShare } = await getShares({
clientId,
authShare: { toRetrieve: true },
deviceShare: { toRetrieve: true },
recoveryShare: { toRetrieve: false },
});
return getUserEtherJsWalletFromShares({
shares: [authShare, deviceShare],
});
}
/**
*
* @param deviceShare retrieves the current share associated with the user's device.
* @returns the requested shares
* @throws if attempting to get {@param deviceShare} when it's not present
*/
export async function getShares<
A extends boolean,
D extends boolean,
R extends boolean,
>({
clientId,
authShare,
deviceShare,
recoveryShare,
}: {
clientId: string;
authShare: { toRetrieve: A };
recoveryShare: R extends true
? {
toRetrieve: R;
recoveryCode: string;
}
: {
toRetrieve: R;
};
deviceShare: { toRetrieve: D };
}): Promise<{
authShare: A extends true ? string : undefined;
recoveryShare: R extends true ? string : undefined;
deviceShare: D extends true ? string : undefined;
}> {
const queryParams: Record<string, boolean> = {};
if (authShare.toRetrieve) {
queryParams.getEncryptedAuthShare = true;
}
if (recoveryShare.toRetrieve) {
queryParams.getEncryptedRecoveryShare = true;
if (!recoveryShare.recoveryCode) {
// purposely using a vague name to prevent people from inspecting url from figuring out what it does
// so as to not cause huge debates on the technicality of the custodial // non-custodial
queryParams.useSealedSecret = true;
}
}
const getShareUrl = new URL(ROUTE_GET_USER_SHARES);
for (const queryKey of Object.keys(queryParams)) {
getShareUrl.searchParams.append(queryKey, queryParams[queryKey].toString());
}
const userShares = await getUserShares(clientId, getShareUrl);
const { authShare: _authShare, maybeEncryptedRecoveryShares } = userShares;
let recoverShareToReturn: string | undefined;
if (recoveryShare.toRetrieve) {
if (!maybeEncryptedRecoveryShares?.length) {
throw new Error("Missing recovery share.");
}
for (const maybeEncryptedRecoveryShare of maybeEncryptedRecoveryShares) {
try {
if (recoveryShare.recoveryCode) {
// for client encrypted share, we attempt to decrypt them
recoverShareToReturn = await decryptShareWeb(
maybeEncryptedRecoveryShare || "",
recoveryShare.recoveryCode || "",
);
} else {
recoverShareToReturn = maybeEncryptedRecoveryShare;
}
// if we get here, decryption was successful, so we stop trying
break;
} catch {}
}
if (!recoverShareToReturn) {
throw new Error("Invalid recovery code.");
}
}
let deviceShareToReturn: string | undefined;
try {
deviceShareToReturn = deviceShare.toRetrieve
? (await getDeviceShare(clientId)).deviceShare
: undefined;
} catch (e) {
throw new Error(DEVICE_SHARE_MISSING_MESSAGE);
}
// The any typecast here to overcome typescript limitation
// see: https://github.com/microsoft/TypeScript/issues/22735
// see: https://github.com/microsoft/TypeScript/issues/22735
return {
authShare: authShare.toRetrieve ? ((_authShare || "") as any) : undefined,
deviceShare: deviceShareToReturn as any,
recoveryShare: recoverShareToReturn as any,
};
}
export function getWalletShareById(
shares: string[],
id: number = DEVICE_SHARE_ID,
) {
return secrets.newShare(id, shares);
}
export function getWalletAddressFromShares(shares: string[]) {
const wallet = getUserEtherJsWalletFromShares({
shares,
});
return wallet.address;
}
export async function setUpShareForNewDevice({
recoveryCode,
clientId,
}: {
recoveryCode: string;
clientId: string;
}): Promise<SetUpWalletRpcReturnType> {
const { recoveryShare, authShare } = await getShares({
clientId,
authShare: { toRetrieve: true },
recoveryShare: { toRetrieve: true, recoveryCode },
deviceShare: { toRetrieve: false },
});
const shares = [recoveryShare, authShare];
const deviceShare = getWalletShareById(shares, DEVICE_SHARE_ID);
const walletAddress = getWalletAddressFromShares([recoveryShare, authShare]);
const maybeDeviceShare = await storeShares({
clientId,
walletAddress,
deviceShare,
});
if (!maybeDeviceShare?.deviceShareStored) {
throw new Error(DEVICE_SHARE_MISSING_MESSAGE);
}
return {
walletAddress,
deviceShareStored: maybeDeviceShare?.deviceShareStored,
isIframeStorageEnabled: false,
};
}
@@ -0,0 +1,10 @@
import { getDefaultProvider } from "ethers";
import { getExistingUserEtherJsWallet } from "./helpers/wallet/retrieval";
export async function getEthersSigner(clientId: string) {
const wallet = await getExistingUserEtherJsWallet(clientId);
const newWallet = wallet.connect(getDefaultProvider());
await newWallet.getChainId();
return newWallet;
}
@@ -0,0 +1,42 @@
import { Chain } from "@thirdweb-dev/chains";
import { WalletOptions } from "@thirdweb-dev/wallets";
import type {
RecoveryShareManagement,
PaperConstructorType,
} from "@paperxyz/embedded-wallet-service-sdk";
export interface EmbeddedConnectorOptions {
chains?: Chain[];
chainId?: number;
email?: string;
phoneNumber?: string;
}
export type EmbeddedWalletOptions = Omit<
WalletOptions<EmbeddedConnectorOptions>,
"clientId"
>;
type EmbeddedAdvanceOptions = {
recoveryShareManagement?: "USER_MANAGED" | "AWS_MANAGED";
};
export type EmbeddedWalletAdditionalOptions = {
emailClientId: string;
chain: Pick<Chain, "chainId" | "rpc">;
advancedOptions?: EmbeddedAdvanceOptions;
styles?: PaperConstructorType<RecoveryShareManagement>["styles"];
};
export interface EmbeddedWalletConnectorOptions {
clientId: string;
chain: Pick<Chain, "chainId" | "rpc">;
chains: Chain[];
advancedOptions?: EmbeddedAdvanceOptions;
styles?: PaperConstructorType<RecoveryShareManagement>["styles"];
}
export interface EmbeddedWalletConnectionArgs {
email?: string;
}
@@ -0,0 +1,249 @@
import {
ConnectUIProps,
useAddress,
useSetConnectedWallet,
useSetConnectionStatus,
} from "@thirdweb-dev/react-core";
import { EmbeddedWallet } from "./EmbeddedWallet";
import React, { useRef, useEffect, useState } from "react";
import {
ActivityIndicator,
NativeSyntheticEvent,
TextInput,
TextInputKeyPressEventData,
} from "react-native";
import { useAppTheme } from "../../../styles/hooks";
import { ConnectWalletHeader } from "../../../components/ConnectWalletFlow/ConnectingWallet/ConnectingWalletHeader";
import Box from "../../../components/base/Box";
import Text from "../../../components/base/Text";
import BaseButton from "../../../components/base/BaseButton";
import * as Clipboard from "expo-clipboard";
const OTP_LENGTH = 6;
export const EmbeddedConnectionUI: React.FC<ConnectUIProps<EmbeddedWallet>> = ({
close,
goBack,
selectionData,
onLocallyConnected,
}) => {
const theme = useAppTheme();
const inputRefs = useRef<(TextInput | null)[]>([]);
const [values, setValues] = useState<string[]>(
new Array(OTP_LENGTH).fill(""),
);
const [checkingOtp, setCheckingOtp] = useState(false);
const [requestingNewOtp, setRequestingNewOtp] = useState(false);
const [errorMessage, setErrorMessage] = useState<string>("");
const setConnectedWallet = useSetConnectedWallet();
const setConnectionStatus = useSetConnectionStatus();
const [focusedIndex, setFocusedIndex] = useState<number | undefined>();
const address = useAddress();
useEffect(() => {
if (address) {
setCheckingOtp(false);
close();
}
}, [address, close]);
useEffect(() => {
if (
values.length === OTP_LENGTH &&
values.every((v) => v.length === 1) &&
selectionData
) {
setCheckingOtp(true);
setErrorMessage("");
setFocusedIndex(undefined);
const otp = values.join("");
setTimeout(() => {
(selectionData.emailWallet as EmbeddedWallet)
.validateEmailOTP(otp)
.then(async (response) => {
if (response?.success) {
if (onLocallyConnected) {
onLocallyConnected(selectionData.emailWallet);
} else {
await setConnectedWallet(selectionData.emailWallet);
setConnectionStatus("connected");
}
} else {
clearCode();
setErrorMessage(response?.error || "Error validating the code");
setCheckingOtp(false);
setFocusedIndex(undefined);
}
})
.catch((error) => {
clearCode();
console.error("Error validating otp: ", error);
setErrorMessage("Error validating the code");
setCheckingOtp(false);
setFocusedIndex(undefined);
});
}, 0);
}
}, [
close,
onLocallyConnected,
selectionData,
setConnectedWallet,
setConnectionStatus,
values,
]);
const handleInputChange = async (value: string, index: number) => {
if (value !== "") {
const copiedContent = await Clipboard.getStringAsync();
if (copiedContent.length === 6 && /^\d+$/.test(copiedContent)) {
const newValues = [...copiedContent];
for (let i = 0; i < 6; i++) {
inputRefs.current[i]?.setNativeProps({ text: newValues[i] });
}
setValues(newValues);
return;
}
}
const newValues = [...values];
newValues[index] = value;
setValues(newValues);
if (value === "" && index > 0) {
inputRefs.current[index - 1]?.focus();
} else if (value.length === 1 && /^[0-9]$/.test(value)) {
if (index < 5) {
inputRefs.current[index + 1]?.focus();
}
}
};
const handleKeyPress = (
e: NativeSyntheticEvent<TextInputKeyPressEventData>,
index: number,
) => {
if (e.nativeEvent.key === "Backspace" && index > 0) {
inputRefs.current[index - 1]?.focus();
}
};
const clearCode = () => {
setValues([]);
setFocusedIndex(undefined);
for (const inputRef of inputRefs.current) {
inputRef?.clear();
}
};
const onRequestNewCodePress = () => {
clearCode();
setErrorMessage("");
setFocusedIndex(undefined);
setRequestingNewOtp(true);
(selectionData.emailWallet as EmbeddedWallet)
.sendEmailOTP(selectionData.email)
.then(() => {})
.catch((error) => {
clearCode();
console.error("Error requesting code: ", error);
setErrorMessage("Error requesting a new code");
})
.finally(() => {
setRequestingNewOtp(false);
});
};
return (
<Box marginHorizontal="xl">
<ConnectWalletHeader
middleContent={<Text variant="header">Sign In</Text>}
subHeaderText={"Please enter the code sent to"}
onBackPress={goBack}
onClose={close}
/>
<Text
variant="subHeader"
textAlign="center"
fontWeight="700"
color="textPrimary"
>
{selectionData?.email}
</Text>
<Box
mt="sm"
flexDirection="row"
height={50}
width={"100%"}
marginTop="xl"
mb="md"
justifyContent="space-evenly"
>
{Array.from({ length: OTP_LENGTH }, (_, index) => (
<Box
key={index.toString()}
flex={1}
borderColor={
focusedIndex === index ? "accentButtonColor" : "iconPrimary"
}
marginHorizontal="xxs"
borderWidth={2}
justifyContent="center"
alignItems="stretch"
borderRadius="md"
>
<TextInput
ref={(ref) => (inputRefs.current[index] = ref)}
style={{
fontSize: 20,
color: theme.colors.textPrimary,
textAlign: "center",
height: 50,
}}
keyboardType="number-pad"
editable={!checkingOtp}
selectTextOnFocus={true}
onFocus={() => setFocusedIndex(index)}
maxLength={1}
returnKeyType={index === 5 ? "done" : "next"}
onChangeText={(value) => handleInputChange(value, index)}
onKeyPress={(e) => handleKeyPress(e, index)}
/>
</Box>
))}
</Box>
{errorMessage ? (
<Text variant="error" numberOfLines={1}>
{errorMessage}
</Text>
) : (
<Box height={20} />
)}
{checkingOtp ? (
<ActivityIndicator size="small" />
) : (
<BaseButton
mt="sm"
alignItems="center"
height={theme.textVariants.bodySmallSecondary.fontSize}
onPress={onRequestNewCodePress}
>
{requestingNewOtp ? (
<ActivityIndicator
size={"small"}
color={theme.colors.linkPrimary}
/>
) : (
<Text variant="bodySmallSecondary" color="linkPrimary">
Request new code
</Text>
)}
</BaseButton>
)}
</Box>
);
};
@@ -0,0 +1,127 @@
import React, { useEffect, useState } from "react";
import { EmbeddedWallet } from "./EmbeddedWallet";
import { ActivityIndicator } from "react-native";
import { useAppTheme } from "../../../styles/hooks";
import {
SelectUIProps,
useCreateWalletInstance,
} from "@thirdweb-dev/react-core";
import Box from "../../../components/base/Box";
import Text from "../../../components/base/Text";
import BaseButton from "../../../components/base/BaseButton";
import { TextInput } from "../../../components/base/TextInput";
/**
* UI for selecting wallet - this UI is rendered in the wallet selection screen
*/
export const EmailSelectionUI: React.FC<SelectUIProps<EmbeddedWallet>> = ({
onSelect,
walletConfig,
}) => {
const theme = useAppTheme();
const [email, setEmail] = useState<string>("");
const [errorMessage, setErrorMessage] = useState<string>("");
const [isFetching, setIsFetching] = useState<boolean>(false);
const createWalletInstance = useCreateWalletInstance();
const [emailWallet, setEmailWallet] = useState<EmbeddedWallet | null>(null);
useEffect(() => {
const emailWalletInstance = createWalletInstance(
walletConfig,
) as EmbeddedWallet;
setEmailWallet(emailWalletInstance);
}, [createWalletInstance, walletConfig]);
const validateEmail = (emailToValidate: string) => {
const pattern = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
return pattern.test(emailToValidate);
};
const handleNetworkCall = () => {
if (validateEmail(email)) {
setErrorMessage("");
setIsFetching(true);
emailWallet
?.sendEmailOTP(email)
.then((response) => {
onSelect({
...response,
email,
emailWallet,
});
})
.catch((error) => {
console.error(error);
setErrorMessage(`Error processing email: ${error.message}`);
})
.finally(() => {
setIsFetching(false);
});
} else {
setIsFetching(false);
setErrorMessage("Please enter a valid email address.");
}
};
return (
<Box paddingHorizontal="xl" mt="lg">
<TextInput
textInputProps={{
placeholder: "Enter your email address",
placeholderTextColor: theme.colors.textSecondary,
onChangeText: setEmail,
style: {
fontSize: 14,
color: theme.colors.textPrimary,
lineHeight: 16,
padding: 0,
flex: 1,
},
value: email,
keyboardType: "email-address",
returnKeyType: "done",
autoCapitalize: "none",
autoCorrect: false,
autoComplete: "off",
clearTextOnFocus: false,
}}
containerProps={{
paddingHorizontal: "sm",
paddingVertical: "sm",
justifyContent: "flex-start",
}}
/>
<BaseButton
mt="md"
paddingVertical="md"
borderRadius="lg"
borderWidth={1}
borderColor="border"
backgroundColor="accentButtonColor"
onPress={handleNetworkCall}
>
{isFetching ? (
<ActivityIndicator
size={"small"}
color={theme.colors.accentButtonTextColor}
/>
) : (
<Text
variant="bodySmall"
color="accentButtonTextColor"
fontWeight="700"
>
Continue
</Text>
)}
</BaseButton>
{errorMessage ? (
<Text variant="error" mt="xxs">
{errorMessage}
</Text>
) : null}
</Box>
);
};
@@ -0,0 +1,111 @@
import {
WalletOptions,
AbstractClientWallet,
EmbeddedWalletAdditionalOptions,
walletIds,
} from "@thirdweb-dev/wallets";
import type { EmbeddedWalletConnector as EmbeddedConnectorType } from "../../connectors/embedded-wallet/embedded-connector";
import { EmbeddedWalletConnectionArgs } from "../../connectors/embedded-wallet/types";
import { EmbeddedWalletConnector } from "../../connectors/embedded-wallet/embedded-connector";
import { EMAIL_WALLET_ICON } from "../../../assets/svgs";
export type EmbeddedWalletOptions =
WalletOptions<EmbeddedWalletAdditionalOptions>;
export class EmbeddedWallet extends AbstractClientWallet<
EmbeddedWalletOptions,
EmbeddedWalletConnectionArgs
> {
connector?: EmbeddedConnectorType;
options: EmbeddedWalletOptions;
static meta = {
name: "Embedded Wallet",
iconURL: EMAIL_WALLET_ICON,
};
static id = walletIds.embeddedWallet;
constructor(options: EmbeddedWalletOptions) {
super(EmbeddedWallet.id, options);
this.options = options;
this.initializeConnector();
this.setupListeners();
}
async getConnector(): Promise<EmbeddedConnectorType> {
if (!this.connector) {
return await this.initializeConnector();
}
return this.connector;
}
// my methods
initializeConnector() {
this.connector = new EmbeddedWalletConnector({
...this.options,
clientId: this.options.clientId,
chains: this.chains,
});
return this.connector;
}
async validateEmailOTP(otp: string) {
return this.connector?.validateEmailOtp(otp);
}
async sendEmailOTP(email: string) {
return this.connector?.sendEmailOtp(email);
}
onConnected = () => {
this.emit("message", { type: "connected" });
};
onDisconnect = () => {
this.removeListeners();
};
onChange = async (payload: any) => {
if (payload.chain) {
// chain changed
} else if (payload.account) {
//account change
}
};
getEmail() {
return this.connector?.getEmail();
}
onEmailSent = ({ email }: { email: string }) => {
this.emit("message", { type: "emailSent", data: email });
};
setupListeners() {
if (!this.connector) {
return;
}
this.removeListeners();
this.connector.on("emailSent", this.onEmailSent);
this.connector.on("connected", this.onConnected);
this.connector.on("disconnect", this.onDisconnect);
this.connector.on("change", this.onChange);
}
removeListeners() {
if (!this.connector) {
return;
}
this.connector.removeListener("emailSent", this.onEmailSent);
this.connector.removeListener("connected", this.onConnected);
this.connector.removeListener("disconnect", this.onDisconnect);
this.connector.removeListener("change", this.onChange);
}
}
@@ -0,0 +1,34 @@
import { EmbeddedWallet } from "./EmbeddedWallet";
import {
SelectUIProps,
WalletConfig,
WalletOptions,
} from "@thirdweb-dev/react-core";
import { EmbeddedConnectionUI } from "./EmbeddedConnectionUI";
import { EmailSelectionUI } from "./EmbeddedSelectionUI";
export type EmbeddedWalletConfig = {
recommended?: boolean;
};
export const embeddedWallet = (
config?: EmbeddedWalletConfig,
): WalletConfig<EmbeddedWallet> => {
const selectUI = (props: SelectUIProps<EmbeddedWallet>) => (
<EmailSelectionUI {...props} />
);
return {
id: EmbeddedWallet.id,
meta: EmbeddedWallet.meta,
create(options: WalletOptions) {
return new EmbeddedWallet({
...options,
clientId: options.clientId || "",
});
},
selectUI: selectUI,
connectUI: EmbeddedConnectionUI,
recommended: config?.recommended,
};
};
@@ -82,12 +82,12 @@ const MagicSelectionUI: React.FC<SelectUIProps<MagicLink>> = (props) => {
}}
containerProps={{
paddingHorizontal: "sm",
paddingVertical: "md",
paddingVertical: "sm",
}}
/>
<BaseButton
mt="md"
paddingVertical="xmd"
paddingVertical="md"
borderRadius="lg"
borderWidth={1}
borderColor="border"
@@ -164,6 +164,7 @@ const MagicConnectionUI: React.FC<
return (
<ConnectingWallet
subHeaderText=""
wallet={walletConfig}
onClose={close}
onBackPress={goBack}
@@ -20,7 +20,7 @@ export const smartWallet = (
wcStorage: createSyncStorage("smart-wallet"),
}),
connectUI(props) {
return <SmartWalletFlow {...props} />;
return <SmartWalletFlow {...props} personalWalletConfig={wallet} />;
},
selectUI: WalletSelectUI
? (props) => {
@@ -1,5 +1,6 @@
import { MMKV } from "react-native-mmkv";
import { WC2Options, WalletConnectBase } from "./WalletConnectBase";
import { WALLETCONNECT_ICON } from "../../../assets/svgs";
const PREFIX = "__TW__WALLET__CONNECT__";
@@ -7,8 +8,7 @@ export class WalletConnect extends WalletConnectBase {
static id = "WalletConnect" as const;
static meta = {
name: "WalletConnect",
iconURL:
"ipfs://QmX58KPRaTC9JYZ7KriuBzeoEaV2P9eZcA3qbFnTHZazKw/wallet-connect.svg",
iconURL: WALLETCONNECT_ICON,
links: {
native: "wc:",
universal: "wc:",
@@ -30,7 +30,7 @@ export const WalletConnectButton = ({
onPress={onWalletPress}
>
{isAnimating ? (
<WalletLoadingThumbnail>
<WalletLoadingThumbnail imageSize={55}>
<Image
alt={item.name}
source={{ uri: item.iconURL }}
@@ -58,7 +58,12 @@ export const WalletConnectButton = ({
]}
/>
)}
<Text variant="bodySmallSecondary" fontSize={12} numberOfLines={1}>
<Text
variant="bodySmallSecondary"
fontSize={12}
numberOfLines={1}
mt="xxs"
>
{item.name.split(" ")[0]}
</Text>
</BaseButton>
@@ -20,8 +20,8 @@ import {
} from "@thirdweb-dev/react-core";
import { WalletConnect } from "./WalletConnect";
import { useAppTheme } from "../../../styles/hooks";
import { ConnectWalletHeader } from "../../../components/ConnectWalletFlow/ConnectingWallet/ConnectingWalletHeader";
import { WalletConnectButton } from "./WalletConnectButton";
import { ModalHeaderTextClose } from "../../../components/base";
type WCWallet = {
iconURL: string;
@@ -158,10 +158,11 @@ export function WalletConnectUI({
<View
style={[styles.modal, { backgroundColor: theme.colors.background }]}
>
<ConnectWalletHeader
subHeaderText={""}
<ModalHeaderTextClose
onBackPress={goBack}
headerText="WalletConnect"
onClose={onClosePress}
paddingHorizontal="md"
/>
<View style={styles.explorerContainer}>
{loading ? (
@@ -175,27 +176,27 @@ export function WalletConnectUI({
fadingEdgeLength={20}
stickyHeaderIndices={[0]}
ListHeaderComponent={
<Box
borderColor="border"
borderWidth={0.5}
backgroundColor="background"
flex={1}
flexDirection="row"
borderRadius="md"
alignItems="center"
mb="sm"
padding="xs"
width={"100%"}
>
<TextInput
onChangeText={onChangeText}
placeholder="Search Wallets"
placeholderTextColor={theme.colors.textSecondary}
style={{
...styles.textInput,
color: theme.colors.textSecondary,
}}
/>
<Box backgroundColor="background" mb="sm">
<Box
borderColor="border"
borderWidth={0.5}
flex={1}
flexDirection="row"
borderRadius="md"
alignItems="center"
marginHorizontal="md"
padding="xs"
>
<TextInput
onChangeText={onChangeText}
placeholder="Search Wallets"
placeholderTextColor={theme.colors.textSecondary}
style={{
...styles.textInput,
color: theme.colors.textSecondary,
}}
/>
</Box>
</Box>
}
ListEmptyComponent={
@@ -236,7 +237,7 @@ const styles = StyleSheet.create({
paddingBottom: 12,
},
listContentContainer: {
paddingBottom: 12,
paddingBottom: 10,
flexGrow: 1,
},
emptyContainer: {
+17
View File
@@ -1,5 +1,22 @@
# @thirdweb-dev/react
## 3.16.1
### Patch Changes
- [#1637](https://github.com/thirdweb-dev/js/pull/1637) [`54f83a50`](https://github.com/thirdweb-dev/js/commit/54f83a5013ed65ddd5a787e13ba7e5d86625537d) Thanks [@MananTank](https://github.com/MananTank)! - add SignerWallet
- [#1682](https://github.com/thirdweb-dev/js/pull/1682) [`eb9e9f0c`](https://github.com/thirdweb-dev/js/commit/eb9e9f0ce8019570a00660724a9bf669910959b9) Thanks [@MananTank](https://github.com/MananTank)! - - Always show "Connected to Smart Wallet" text in ConnectWallet dropdown but only link to dashboard if it is deployed
- Show QR code in the Receive funds screen on mobile too
- [#1687](https://github.com/thirdweb-dev/js/pull/1687) [`fd378ec3`](https://github.com/thirdweb-dev/js/commit/fd378ec3e41c17bca6b67ff2969d3591e4e0f047) Thanks [@MananTank](https://github.com/MananTank)! - ConnectWallet UI Improvements for OTP screen and other minor UI tweaks
- Updated dependencies [[`54f83a50`](https://github.com/thirdweb-dev/js/commit/54f83a5013ed65ddd5a787e13ba7e5d86625537d), [`a9b4b0c5`](https://github.com/thirdweb-dev/js/commit/a9b4b0c5d875dec660694466e5e322cc574bb21b), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3), [`96e832cc`](https://github.com/thirdweb-dev/js/commit/96e832cc80692da38279c53f1289265b3728cb19), [`b16c09df`](https://github.com/thirdweb-dev/js/commit/b16c09df75c7193a91b832db7d9c92612ae09357), [`6897ad65`](https://github.com/thirdweb-dev/js/commit/6897ad6502d585d55a8c7b2312b4af30663336c3), [`ee028e12`](https://github.com/thirdweb-dev/js/commit/ee028e12092fd306f076f6ea1d49a2295802dd6b), [`d28b1c0f`](https://github.com/thirdweb-dev/js/commit/d28b1c0f1e1e53eedc8f331be555e22b64fb920d), [`c085d690`](https://github.com/thirdweb-dev/js/commit/c085d69060c68b3335761bdb2cc0c3e082548702), [`de05c2da`](https://github.com/thirdweb-dev/js/commit/de05c2da174a69315f2d34dd32a811bbd9a0b604), [`bdb2ccc7`](https://github.com/thirdweb-dev/js/commit/bdb2ccc7a66c33ec5dc331b6fa792e6361769e88), [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3)]:
- @thirdweb-dev/wallets@1.3.1
- @thirdweb-dev/sdk@3.10.63
- @thirdweb-dev/react-core@3.16.1
## 3.16.0
### Minor Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/react",
"version": "3.16.0",
"version": "3.16.1",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/react",
"author": "thirdweb eng <[email protected]>",
"license": "Apache-2.0",
+1 -1
View File
@@ -8,7 +8,7 @@ const darkColors = {
primaryText: mauveDark.mauve12,
secondaryText: mauveDark.mauve10,
danger: tomato.tomato9,
success: green.green7,
success: green.green8,
overlay: "rgba(0, 0, 0, 0.7)",
accentText: "#3385FF",
accentBg: "hsl(216 100% 50%)",
@@ -6,15 +6,17 @@ import {
import { WalletUIStatesProvider } from "./wallet-ui-states-provider";
import { ConnectModal } from "../../wallet/ConnectWallet/Modal/ConnectModal";
import { ThemeObjectOrType } from "../../design-system";
import { PropsWithChildren } from "react";
import { PropsWithChildren, useMemo } from "react";
import type { Chain, defaultChains } from "@thirdweb-dev/chains";
import { defaultWallets } from "../../wallet/wallets/defaultWallets";
import { CustomThemeProvider } from "../../design-system/CustomThemeProvider";
import { signerWallet } from "../../wallet/wallets/signerWallet";
import { Signer } from "ethers";
interface ThirdwebProviderProps<TChains extends Chain[]>
extends Omit<
ThirdwebProviderCoreProps<TChains>,
"createWalletStorage" | "supportedWallets" | "signer" | "theme"
"createWalletStorage" | "supportedWallets" | "theme"
> {
/**
* Wallets supported by the dApp
@@ -36,6 +38,8 @@ interface ThirdwebProviderProps<TChains extends Chain[]>
* @defaultValue "dark"
*/
theme?: ThemeObjectOrType;
signer?: Signer;
}
/**
@@ -64,12 +68,18 @@ export const ThirdwebProvider = <
>({
supportedWallets,
children,
signer,
theme: _theme,
...restProps
}: PropsWithChildren<ThirdwebProviderProps<TChains>>) => {
const wallets: WalletConfig[] = supportedWallets || defaultWallets;
const theme = _theme || "dark";
const signerWalletConfig = useMemo(
() => (signer ? (signerWallet(signer) as WalletConfig<any>) : undefined),
[signer],
);
return (
<WalletUIStatesProvider theme={theme}>
<CustomThemeProvider theme={theme}>
@@ -77,6 +87,7 @@ export const ThirdwebProvider = <
{...restProps}
theme={typeof theme === "string" ? theme : theme.type}
supportedWallets={wallets}
signerWallet={signerWalletConfig}
>
{children}
<ConnectModal />
@@ -40,6 +40,7 @@ import {
useSupportedChains,
useWallet,
WalletInstance,
useENS,
} from "@thirdweb-dev/react-core";
import { useEffect, useState } from "react";
import {
@@ -58,7 +59,6 @@ import { Link, Text } from "../../components/text";
import { SendFunds } from "./SendFunds";
import { SupportedTokens } from "./defaultTokens";
import { ReceiveFunds } from "./ReceiveFunds";
import { useENS } from "../hooks/useENS";
import { smartWalletIcon } from "./icons/dataUris";
export type DropDownPosition = {
@@ -758,46 +758,56 @@ function ConnectedToSmartWallet() {
const chain = useChain();
const address = useAddress();
const [showConnectedToSmartWallet, setShowConnectedToSmartWallet] =
useState(false);
const [isSmartWalletDeployed, setIsSmartWalletDeployed] = useState(false);
useEffect(() => {
if (activeWallet && activeWallet.walletId === walletIds.smartWallet) {
const smartWallet = activeWallet as SmartWallet;
smartWallet.isDeployed().then((isDeployed) => {
setShowConnectedToSmartWallet(isDeployed);
setIsSmartWalletDeployed(isDeployed);
});
} else {
setShowConnectedToSmartWallet(false);
setIsSmartWalletDeployed(false);
}
}, [activeWallet]);
if (showConnectedToSmartWallet && chain && address) {
const content = (
<Container
flex="row"
gap="xs"
center="y"
style={{
width: "100%",
justifyContent: "space-between",
}}
>
<Container flex="row" gap="xs" center="y">
<ActiveDot />
Connected to Smart Wallet
</Container>
{isSmartWalletDeployed && (
<ChevronRightIcon width={iconSize.sm} height={iconSize.sm} />
)}
</Container>
);
if (chain && address && activeWallet?.walletId === walletIds.smartWallet) {
return (
<>
<Link
color="secondaryText"
hoverColor="primaryText"
href={`https://thirdweb.com/${chain.slug}/${address}/account`}
target="_blank"
size="sm"
>
<Container
flex="row"
gap="xs"
center="y"
style={{
width: "100%",
justifyContent: "space-between",
}}
{isSmartWalletDeployed ? (
<Link
color="secondaryText"
hoverColor="primaryText"
href={`https://thirdweb.com/${chain.slug}/${address}/account`}
target="_blank"
size="sm"
>
<Container flex="row" gap="xs" center="y">
<ActiveDot />
Connected to Smart Wallet
</Container>
<ChevronRightIcon width={iconSize.sm} height={iconSize.sm} />
</Container>
</Link>
{content}
</Link>
) : (
<Text size="sm"> {content}</Text>
)}
<Spacer y="md" />
</>
);
@@ -25,7 +25,7 @@ import type { Chain } from "@thirdweb-dev/chains";
import Fuse from "fuse.js";
import { Button } from "../../components/buttons";
import { useEffect } from "react";
import { Container, Line, noScrollBar } from "../../components/basic";
import { Container, Line } from "../../components/basic";
import { Text } from "../../components/text";
import { ModalTitle } from "../../components/modalElements";
import { CustomThemeProvider } from "../../design-system/CustomThemeProvider";
@@ -221,7 +221,13 @@ export const NetworkSelector: React.FC<NetworkSelectorProps> = (props) => {
)}
<Container px="md">
<Tabs.Content className="TabsContent" value="all">
<Tabs.Content
className="TabsContent"
value="all"
style={{
outline: "none",
}}
>
<NetworkTab
allChains={allChains}
type="all"
@@ -233,7 +239,13 @@ export const NetworkSelector: React.FC<NetworkSelectorProps> = (props) => {
/>
</Tabs.Content>
<Tabs.Content className="TabsContent" value="mainnet">
<Tabs.Content
className="TabsContent"
value="mainnet"
style={{
outline: "none",
}}
>
<NetworkTab
allChains={allChains}
type="mainnet"
@@ -245,7 +257,13 @@ export const NetworkSelector: React.FC<NetworkSelectorProps> = (props) => {
/>
</Tabs.Content>
<Tabs.Content className="TabsContent" value="testnet">
<Tabs.Content
className="TabsContent"
value="testnet"
style={{
outline: "none",
}}
>
<NetworkTab
allChains={allChains}
type="testnet"
@@ -327,9 +345,12 @@ const NetworkTab = (props: {
);
return (
<ScrollContainer
<Container
scrollY
animate="fadein"
style={{
height: "330px",
paddingBottom: spacing.lg,
}}
>
{recentChains.length > 0 && (
@@ -374,7 +395,7 @@ const NetworkTab = (props: {
renderChain={props.renderChain}
close={props.close}
/>
</ScrollContainer>
</Container>
);
};
@@ -498,9 +519,11 @@ const NetworkList = /* @__PURE__ */ memo(function NetworkList(props: {
)}
{switchingFailed && (
<Text size="xs" color="danger">
Failed to Switch Network
</Text>
<Container animate="fadein">
<Text size="xs" color="danger">
Failed to Switch Network
</Text>
</Container>
)}
</Container>
</div>
@@ -544,13 +567,6 @@ const SectionLabel = styled.p<{ theme?: Theme }>`
padding: 0 ${spacing.xs};
`;
const ScrollContainer = styled.div<{ theme?: Theme }>`
box-sizing: border-box;
overflow: auto;
padding-bottom: ${spacing.lg};
${noScrollBar};
`;
const NetworkListUl = styled.ul<{ theme?: Theme }>`
padding: 0;
margin: 0;
@@ -7,13 +7,11 @@ import { CopyIcon } from "../../components/CopyIcon";
import styled from "@emotion/styled";
import { Theme, iconSize, radius, spacing } from "../../design-system";
import { QRCode } from "../../components/QRCode";
import { isMobile } from "../../evm/utils/isMobile";
import { Img } from "../../components/Img";
import { useClipboard } from "../../evm/components/hooks/useCopyClipboard";
export function ReceiveFunds(props: { iconUrl: string }) {
const address = useAddress();
const isMob = isMobile();
const { hasCopied, onCopy } = useClipboard(address || "");
return (
@@ -22,24 +20,20 @@ export function ReceiveFunds(props: { iconUrl: string }) {
<Spacer y="xl" />
{!isMob && (
<>
<Container flex="row" center="x">
<QRCode
qrCodeUri={address}
size={310}
QRIcon={
<Img
src={props.iconUrl}
width={iconSize.xxl}
height={iconSize.xxl}
/>
}
<Container flex="row" center="x">
<QRCode
qrCodeUri={address}
size={310}
QRIcon={
<Img
src={props.iconUrl}
width={iconSize.xxl}
height={iconSize.xxl}
/>
</Container>
<Spacer y="xl" />
</>
)}
}
/>
</Container>
<Spacer y="xl" />
<WalletAddressContianer onClick={onCopy}>
<Text color="primaryText" size="md">
@@ -54,20 +48,10 @@ export function ReceiveFunds(props: { iconUrl: string }) {
<Spacer y="lg" />
{!isMob ? (
<Text multiline center>
Copy the wallet address or scan the <br /> QR code to send funds to
this wallet.
</Text>
) : (
<>
<Text multiline center>
Copy the wallet address to <br />
send funds to this wallet
</Text>
<Spacer y="xl" />
</>
)}
<Text multiline center>
Copy the wallet address to <br />
send funds to this wallet
</Text>
</Container>
);
}
@@ -1,4 +1,4 @@
import { useContext, useState } from "react";
import { useContext, useEffect, useRef, useState } from "react";
import { Img } from "../../components/Img";
import {
noScrollBar,
@@ -91,6 +91,14 @@ export const WalletSelector: React.FC<{
</Button>
);
// prevent accidental clicks on the TW icon when clicking on back icon from previous screen
const enableTWIconLink = useRef(false);
useEffect(() => {
setTimeout(() => {
enableTWIconLink.current = true;
}, 1000);
}, []);
const twTitle = (
<Container gap="xxs" center="y" flex="row">
{modalConfig.titleIconUrl === undefined ? (
@@ -103,6 +111,11 @@ export const WalletSelector: React.FC<{
display: "flex",
alignItems: "center",
}}
onClick={(e) => {
if (!enableTWIconLink.current) {
e.preventDefault();
}
}}
>
<TWIcon size={iconSize.md} />
</Link>
@@ -6,10 +6,10 @@ import { FadeIn } from "../../../components/FadeIn";
import { OTPInput } from "../../../components/OTPInput";
import { Spacer } from "../../../components/Spacer";
import { Spinner } from "../../../components/Spinner";
import { Container, ModalHeader } from "../../../components/basic";
import { Button } from "../../../components/buttons";
import { Container, Line, ModalHeader } from "../../../components/basic";
import { Text } from "../../../components/text";
import { Theme, fontSize } from "../../../design-system";
import { Button } from "../../../components/buttons";
type EmbeddedWalletOTPLoginUIProps = ConnectUIProps<EmbeddedWallet>;
@@ -22,6 +22,7 @@ export const EmbeddedWalletOTPLoginUI: React.FC<
useWalletContext();
const [wallet, setWallet] = useState<EmbeddedWallet | null>(null);
const isWideModal = props.modalSize === "wide";
const [verifyStatus, setVerifyStatus] = useState<
"verifying" | "invalid" | "valid" | "idle"
@@ -31,8 +32,6 @@ export const EmbeddedWalletOTPLoginUI: React.FC<
"sending" | "sent" | "error"
>("sending");
const recoveryCodeRequired = false;
const sendEmail = useCallback(async () => {
setOtpInput("");
setVerifyStatus("idle");
@@ -55,15 +54,15 @@ export const EmbeddedWalletOTPLoginUI: React.FC<
}
}, [createWalletInstance, email, props.walletConfig]);
const handleSubmit = () => {
if (!sendEmailOtpStatus || otpInput.length !== 6) {
const handleSubmit = (otp: string) => {
if (sendEmailOtpStatus !== "sent" || otp.length !== 6) {
return;
}
verifyCodes();
verifyCodes(otp);
};
const verifyCodes = async () => {
const verifyCodes = async (otp: string) => {
setVerifyStatus("idle");
if (!wallet) {
@@ -76,7 +75,7 @@ export const EmbeddedWalletOTPLoginUI: React.FC<
await wallet.connect({
loginType: "headless_email_otp_verification",
email,
otp: otpInput,
otp,
});
setConnectedWallet(wallet);
@@ -98,8 +97,10 @@ export const EmbeddedWalletOTPLoginUI: React.FC<
}, [sendEmail]);
return (
<Container fullHeight flex="column" p="lg" animate="fadein">
<ModalHeader title="Sign in" onBack={props.goBack} />
<Container fullHeight flex="column" animate="fadein">
<Container p="lg">
<ModalHeader title="Sign in" onBack={props.goBack} />
</Container>
<Container expand flex="column" center="y">
<form
@@ -112,11 +113,11 @@ export const EmbeddedWalletOTPLoginUI: React.FC<
textAlign: "center",
}}
>
<Spacer y="xxl" />
{!isWideModal && <Spacer y="xl" />}
<Text>Enter the OTP sent to</Text>
<Spacer y="sm" />
<Text color="primaryText">{email}</Text>
<Spacer y="xl" />
<Spacer y="xxl" />
</div>
<OTPInput
@@ -125,75 +126,82 @@ export const EmbeddedWalletOTPLoginUI: React.FC<
value={otpInput}
setValue={(value) => {
setOtpInput(value);
setVerifyStatus("idle");
setVerifyStatus("idle"); // reset error
handleSubmit(value);
}}
onEnter={() => {
handleSubmit(otpInput);
}}
onEnter={handleSubmit}
/>
{verifyStatus === "invalid" && (
<FadeIn>
<Spacer y="sm" />
<Container flex="row" center="x">
<Text size="sm" color="danger">
Invalid OTP {recoveryCodeRequired ? "or recovery code" : ""}
</Text>
</Container>
<Spacer y="md" />
<Text size="sm" color="danger" center>
Invalid OTP
</Text>
</FadeIn>
)}
<Spacer y="xl" />
<Spacer y="xxl" />
{verifyStatus === "verifying" ? (
<>
<Spacer y="md" />
<Container flex="row" center="x">
<Spinner size="md" color="accentText" />
<Container px={isWideModal ? "xxl" : "lg"}>
{verifyStatus === "verifying" ? (
<>
<Container flex="row" center="x" animate="fadein">
<Spinner size="lg" color="accentText" />
</Container>
</>
) : (
<Container animate="fadein" key="btn-container">
<Button
onClick={() => handleSubmit(otpInput)}
variant="accent"
type="submit"
style={{
width: "100%",
}}
>
Verify
</Button>
</Container>
<Spacer y="md" />
</>
) : (
<Button
onClick={handleSubmit}
variant="accent"
type="submit"
style={{
width: "100%",
}}
>
Verify
</Button>
)}
)}
</Container>
<Spacer y="lg" />
<Spacer y="xxl" />
{sendEmailOtpStatus === "error" && (
<>
<Text size="sm" center color="danger">
Failed to send OTP
</Text>
<Spacer y="md" />
</>
)}
{!isWideModal && <Line />}
{sendEmailOtpStatus === "sending" && (
<Container
flex="row"
center="both"
gap="xs"
style={{
textAlign: "center",
}}
>
<Text size="sm">Sending OTP</Text>
<Spinner size="xs" color="secondaryText" />
</Container>
)}
<Container p={isWideModal ? undefined : "lg"}>
{sendEmailOtpStatus === "error" && (
<>
<Text size="sm" center color="danger">
Failed to send OTP
</Text>
<Spacer y="md" />
</>
)}
{sendEmailOtpStatus === "sent" && (
<LinkButton onClick={sendEmail} type="button">
Resend OTP
</LinkButton>
)}
{sendEmailOtpStatus === "sending" && (
<Container
flex="row"
center="both"
gap="xs"
style={{
textAlign: "center",
}}
>
<Text size="sm">Sending OTP</Text>
<Spinner size="xs" color="secondaryText" />
</Container>
)}
{sendEmailOtpStatus === "sent" && (
<LinkButton onClick={sendEmail} type="button">
Resend OTP
</LinkButton>
)}
</Container>
</form>
</Container>
</Container>
@@ -206,6 +214,7 @@ const LinkButton = styled.button<{ theme?: Theme }>`
font-size: ${fontSize.sm};
cursor: pointer;
text-align: center;
font-weight: 500;
width: 100%;
&:hover {
color: ${(p) => p.theme.colors.primaryText};
@@ -16,11 +16,13 @@ import { RecoveryShareManagement } from "./types";
type PaperOTPLoginUIProps = ConnectUIProps<PaperWallet> & {
recoveryShareManagement: RecoveryShareManagement;
};
type SentEmailInfo = {
isNewDevice: boolean;
isNewUser: boolean;
recoveryShareManagement: RecoveryShareManagement;
};
export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
const email = props.selectionData;
const [otpInput, setOtpInput] = useState("");
@@ -29,27 +31,27 @@ export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
useWalletContext();
const [wallet, setWallet] = useState<PaperWallet | null>(null);
const isWideModal = props.modalSize === "wide";
const [verifyStatus, setVerifyStatus] = useState<
"verifying" | "invalid" | "valid" | "idle"
>("idle");
const [sentEmailInfo, setSentEmailInfo] = useState<
SentEmailInfo | null | "error"
>(null);
const [sendEmailStatus, setSendEmailStatus] = useState<
SentEmailInfo | "sending" | "error"
>("sending");
const recoveryCodeRequired = !!(
sentEmailInfo &&
sentEmailInfo !== "error" &&
sentEmailInfo.recoveryShareManagement !== "AWS_MANAGED" &&
sentEmailInfo.isNewDevice &&
!sentEmailInfo.isNewUser
typeof sendEmailStatus !== "string" &&
sendEmailStatus.recoveryShareManagement !== "AWS_MANAGED" &&
sendEmailStatus.isNewDevice &&
!sendEmailStatus.isNewUser
);
const sendEmail = useCallback(async () => {
setOtpInput("");
setVerifyStatus("idle");
setSentEmailInfo(null);
setSendEmailStatus("sending");
try {
const _wallet = createWalletInstance(props.walletConfig);
@@ -61,27 +63,27 @@ export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
email: email,
});
setSentEmailInfo({ isNewDevice, isNewUser, recoveryShareManagement });
setSendEmailStatus({ isNewDevice, isNewUser, recoveryShareManagement });
} catch (e) {
console.error(e);
setVerifyStatus("idle");
setSentEmailInfo("error");
setSendEmailStatus("error");
}
}, [createWalletInstance, email, props.walletConfig]);
const handleSubmit = () => {
const handleSubmit = (otp: string) => {
if (recoveryCodeRequired && !recoveryCode) {
return;
}
if (!sentEmailInfo || otpInput.length !== 6) {
if (typeof sendEmailStatus === "string" || otp.length !== 6) {
return;
}
verifyCodes();
verifyCodes(otp);
};
const verifyCodes = async () => {
const verifyCodes = async (otp: string) => {
setVerifyStatus("idle");
if (!wallet) {
@@ -93,7 +95,7 @@ export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
setConnectionStatus("connecting");
await wallet.connect({
email,
otp: otpInput,
otp,
recoveryCode: recoveryCodeRequired ? recoveryCode : undefined,
});
@@ -116,8 +118,10 @@ export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
}, [sendEmail]);
return (
<Container fullHeight flex="column" p="lg" animate="fadein">
<ModalHeader title="Sign in" onBack={props.goBack} />
<Container fullHeight flex="column" animate="fadein">
<Container p="lg">
<ModalHeader title="Sign in" onBack={props.goBack} />
</Container>
<Container expand flex="column" center="y">
<form
@@ -130,7 +134,7 @@ export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
textAlign: "center",
}}
>
<Spacer y="xxl" />
{!isWideModal && <Spacer y="lg" />}
<Text>Enter the OTP sent to</Text>
<Spacer y="sm" />
<Text color="primaryText">{email}</Text>
@@ -143,24 +147,28 @@ export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
value={otpInput}
setValue={(value) => {
setOtpInput(value);
setVerifyStatus("idle");
setVerifyStatus("idle"); // reset error
if (!recoveryCodeRequired) {
handleSubmit(value);
}
}}
onEnter={() => {
handleSubmit(otpInput);
}}
onEnter={handleSubmit}
/>
{recoveryCodeRequired && (
<div
<Container
px="lg"
style={{
textAlign: "center",
}}
>
<Spacer y="xl" />
<Line />
<Spacer y="xl" />
<Spacer y="xxl" />
<Text color="primaryText">New device detected</Text>
<Spacer y="sm" />
<Text
size="sm"
multiline
style={{
maxWidth: "350px",
@@ -170,8 +178,9 @@ export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
signed up
</Text>
<Spacer y="md" />
<Spacer y="lg" />
<Input
sm
autoComplete="off"
required
data-error={verifyStatus === "invalid"}
@@ -184,73 +193,77 @@ export const PaperOTPLoginUI: React.FC<PaperOTPLoginUIProps> = (props) => {
onChange={(e) => setRecoveryCode(e.target.value)}
placeholder="Enter your recovery code"
/>
</div>
</Container>
)}
{verifyStatus === "invalid" && (
<FadeIn>
<Spacer y="sm" />
<Container flex="row" center="x">
<Text size="sm" color="danger">
Invalid OTP {recoveryCodeRequired ? "or recovery code" : ""}
</Text>
</Container>
<Spacer y="md" />
<Text size="sm" color="danger" center>
Invalid OTP {recoveryCodeRequired ? "or recovery code" : ""}
</Text>
</FadeIn>
)}
<Spacer y="xl" />
<Spacer y={recoveryCodeRequired ? "xl" : "xxl"} />
{verifyStatus === "verifying" ? (
<>
<Spacer y="md" />
<Container flex="row" center="x">
<Spinner size="md" color="accentText" />
<Container px={isWideModal ? "xxl" : "lg"}>
{verifyStatus === "verifying" ? (
<>
<Container flex="row" center="x" animate="fadein">
<Spinner size="lg" color="accentText" />
</Container>
</>
) : (
<Container animate="fadein" key="btn-container">
<Button
onClick={() => handleSubmit(otpInput)}
variant="accent"
type="submit"
style={{
width: "100%",
}}
>
Verify
</Button>
</Container>
<Spacer y="md" />
</>
) : (
<Button
onClick={handleSubmit}
variant="accent"
type="submit"
style={{
width: "100%",
}}
>
Verify
</Button>
)}
)}
</Container>
<Spacer y="lg" />
<Spacer y={recoveryCodeRequired ? "xl" : "xxl"} />
{sentEmailInfo === "error" && (
<>
<Text size="sm" center color="danger">
Failed to send OTP
</Text>
<Spacer y="md" />
</>
)}
{!isWideModal && <Line />}
{!sentEmailInfo && (
<Container
flex="row"
center="both"
gap="xs"
style={{
textAlign: "center",
}}
>
<Text size="sm">Sending OTP</Text>
<Spinner size="xs" color="secondaryText" />
</Container>
)}
<Container p={isWideModal ? undefined : "lg"}>
{sendEmailStatus === "error" && (
<>
<Text size="sm" center color="danger">
Failed to send OTP
</Text>
<Spacer y="md" />
</>
)}
{sentEmailInfo && (
<LinkButton onClick={sendEmail} type="button">
Resend OTP
</LinkButton>
)}
{sendEmailStatus === "sending" && (
<Container
flex="row"
center="both"
gap="xs"
style={{
textAlign: "center",
}}
>
<Text size="sm">Sending OTP</Text>
<Spinner size="xs" color="secondaryText" />
</Container>
)}
{typeof sendEmailStatus !== "string" && (
<LinkButton onClick={sendEmail} type="button">
Resend OTP
</LinkButton>
)}
</Container>
</form>
</Container>
</Container>
@@ -0,0 +1,19 @@
import { SignerWallet, WalletOptions } from "@thirdweb-dev/wallets";
import { Signer } from "ethers";
import { WalletConfig } from "@thirdweb-dev/react-core";
export const signerWallet = (signer: Signer): WalletConfig<SignerWallet> => {
return {
id: "signerWallet",
meta: {
name: "Signer",
iconURL:
"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbDpzcGFjZT0icHJlc2VydmUiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiPjxwYXRoIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgZmlsbC1ydWxlPSJldmVub2RkIiBkPSJNMTggNWgyYTIgMiAwIDAgMSAyIDJ2MTJhMiAyIDAgMCAxLTIgMkg0YTIgMiAwIDAgMS0yLTJoLjAyN0EyIDIgMCAwIDEgMiAxOC42NzRWNi43NTRhMiAyIDAgMCAxIDEuNDUtMS45MjNsMTItMy40MjhBMiAyIDAgMCAxIDE4IDMuMzI2VjV6bTAgMnY4LjI0NmEyIDIgMCAwIDEtMS40NSAxLjkyM0wxMC4xNCAxOUgyMFY3aC0yek00IDYuNzU0djExLjkybDEyLTMuNDI4VjMuMzI2TDQgNi43NTR6TTE4IDExVjloMnYyaC0yem0tNS0xYTEgMSAwIDEgMSAwLTIgMSAxIDAgMCAxIDAgMnoiIHN0eWxlPSJmaWxsOiByZ2IoMTY5LCAyMDQsIDIyNyk7Ij48L3BhdGg+PC9zdmc+",
},
create: (options: WalletOptions) =>
new SignerWallet({
...options,
signer,
}),
};
};
+22
View File
@@ -1,5 +1,27 @@
# @thirdweb-dev/sdk
## 3.10.63
### Patch Changes
- [#1670](https://github.com/thirdweb-dev/js/pull/1670) [`a9b4b0c5`](https://github.com/thirdweb-dev/js/commit/a9b4b0c5d875dec660694466e5e322cc574bb21b) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Expose proxy resolver helper function
- [#1681](https://github.com/thirdweb-dev/js/pull/1681) [`c7e7ec95`](https://github.com/thirdweb-dev/js/commit/c7e7ec9502b46312d36cad5177c4f4a50c34f1a3) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix error handling when wallets have no funds
- [#1667](https://github.com/thirdweb-dev/js/pull/1667) [`96e832cc`](https://github.com/thirdweb-dev/js/commit/96e832cc80692da38279c53f1289265b3728cb19) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Improve data fetching for erc20 interfaces
- [#1674](https://github.com/thirdweb-dev/js/pull/1674) [`b16c09df`](https://github.com/thirdweb-dev/js/commit/b16c09df75c7193a91b832db7d9c92612ae09357) Thanks [@joaquim-verges](https://github.com/joaquim-verges)! - Fix error on waiting for receipt after gasless tx for certain chains
- [#1678](https://github.com/thirdweb-dev/js/pull/1678) [`6897ad65`](https://github.com/thirdweb-dev/js/commit/6897ad6502d585d55a8c7b2312b4af30663336c3) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Performance improvement to various function for ERC721
- [#1672](https://github.com/thirdweb-dev/js/pull/1672) [`ee028e12`](https://github.com/thirdweb-dev/js/commit/ee028e12092fd306f076f6ea1d49a2295802dd6b) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Improve data fetching for gas & transaction methods
- [#1666](https://github.com/thirdweb-dev/js/pull/1666) [`d28b1c0f`](https://github.com/thirdweb-dev/js/commit/d28b1c0f1e1e53eedc8f331be555e22b64fb920d) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Improve data fetching for some ERC721 modules
- [#1679](https://github.com/thirdweb-dev/js/pull/1679) [`de05c2da`](https://github.com/thirdweb-dev/js/commit/de05c2da174a69315f2d34dd32a811bbd9a0b604) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Add unit test for getting all owners of ERC721 collection
- [#1668](https://github.com/thirdweb-dev/js/pull/1668) [`bdb2ccc7`](https://github.com/thirdweb-dev/js/commit/bdb2ccc7a66c33ec5dc331b6fa792e6361769e88) Thanks [@kien-ngo](https://github.com/kien-ngo)! - Slight improvement for getContract() and getContractFromAbi()
## 3.10.62
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@thirdweb-dev/sdk",
"version": "3.10.62",
"version": "3.10.63",
"description": "The main thirdweb SDK.",
"repository": "https://github.com/thirdweb-dev/js/tree/main/packages/sdk",
"license": "Apache-2.0",

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