From 3ee78ae01de15129350096e7d823649ffd7d8e87 Mon Sep 17 00:00:00 2001 From: Leonardo de Jesus Diz Conde Date: Wed, 18 Oct 2023 17:30:04 -0300 Subject: [PATCH] CU-86a0ytmta - Setup Lint, Prettier, Githook (rush) --- common/config/rush/command-line.json | 4 +- .../src/components/HelloWorld.tsx | 122 +++++++++++++---- examples/wc-dapp-vite-vanilla/main.js | 67 ++++++++-- examples/wc-wallet-react/config-overrides.js | 14 +- examples/wc-wallet-react/images.d.ts | 14 +- examples/wc-wallet-react/src/App.tsx | 61 ++++----- .../src/components/AccountEntry.tsx | 125 ++++++++---------- .../src/components/ConnectDapp.tsx | 117 +++++++--------- .../src/components/DefaultCard.tsx | 34 ++--- .../wc-wallet-react/src/components/Header.tsx | 84 ++++++------ .../wc-wallet-react/src/components/Peer.tsx | 8 +- .../src/components/ProposalCard.tsx | 36 +++-- .../src/components/RequestCard.tsx | 75 +++++------ .../src/components/Scanner.tsx | 66 ++++----- .../src/components/icon/LogoutIcon.tsx | 8 +- .../wc-wallet-react/src/constants/default.ts | 56 ++++---- .../wc-wallet-react/src/constants/index.ts | 2 +- .../src/context/AccountContext.tsx | 54 ++++---- .../wc-wallet-react/src/helpers/FileHelper.ts | 119 ++++++++--------- .../src/helpers/WalletConnectNeonAdapter.ts | 15 +-- examples/wc-wallet-react/src/index.tsx | 20 +-- examples/wc-wallet-react/src/types.ts | 8 +- packages/wallet-connect-sdk-core/src/index.ts | 10 +- .../wallet-connect-sdk-react/src/index.tsx | 10 +- .../wallet-connect-sdk-wallet-core/src/sdk.ts | 15 ++- .../src/types.ts | 5 +- prettier.config.js | 10 -- 27 files changed, 607 insertions(+), 552 deletions(-) delete mode 100644 prettier.config.js diff --git a/common/config/rush/command-line.json b/common/config/rush/command-line.json index 39bfb4a..b3f09e2 100644 --- a/common/config/rush/command-line.json +++ b/common/config/rush/command-line.json @@ -14,7 +14,7 @@ "summary": "Used by the pre-commit Git hook. This command invokes Prettier to reformat staged changes.", "safeForSimultaneousRushProcesses": true, "autoinstallerName": "rush-format", - "shellCommand": "prettier . --check && npm run lint -p --prefix ./packages/wallet-connect-sdk-core && npm run lint -p --prefix ./packages/wallet-connect-sdk-react && npm run lint -p --prefix ./packages/wallet-connect-sdk-wallet-core && npm run lint -p --prefix ./packages/wallet-connect-sdk-wallet-react && npm run lint -p --prefix ./e2e" + "shellCommand": "prettier . --check --config .prettierrc && npm run lint -p --prefix ./packages/wallet-connect-sdk-core && npm run lint -p --prefix ./packages/wallet-connect-sdk-react && npm run lint -p --prefix ./packages/wallet-connect-sdk-wallet-core && npm run lint -p --prefix ./packages/wallet-connect-sdk-wallet-react && npm run lint -p --prefix ./e2e" }, { "name": "format", @@ -22,7 +22,7 @@ "summary": "Used by the pre-commit Git hook. This command invokes Prettier to reformat staged changes.", "safeForSimultaneousRushProcesses": true, "autoinstallerName": "rush-format", - "shellCommand": "prettier . --write && npm run format -p --prefix ./packages/wallet-connect-sdk-core && npm run format -p --prefix ./packages/wallet-connect-sdk-react && npm run format -p --prefix ./packages/wallet-connect-sdk-wallet-core && npm run format -p --prefix ./packages/wallet-connect-sdk-wallet-react && npm run format -p --prefix ./e2e" + "shellCommand": "prettier . --write --config .prettierrc && npm run format -p --prefix ./packages/wallet-connect-sdk-core && npm run format -p --prefix ./packages/wallet-connect-sdk-react && npm run format -p --prefix ./packages/wallet-connect-sdk-wallet-core && npm run format -p --prefix ./packages/wallet-connect-sdk-wallet-react && npm run format -p --prefix ./e2e" } ] } diff --git a/examples/wc-dapp-react/src/components/HelloWorld.tsx b/examples/wc-dapp-react/src/components/HelloWorld.tsx index cb6879d..6c3bcc9 100644 --- a/examples/wc-dapp-react/src/components/HelloWorld.tsx +++ b/examples/wc-dapp-react/src/components/HelloWorld.tsx @@ -70,7 +70,12 @@ function HelloWorld() { { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'balanceOf', - args: [{ type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }], + args: [ + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + ], }, ], signers: [{ scopes: 1 }], @@ -87,10 +92,22 @@ function HelloWorld() { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'transfer', args: [ - { type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }, - { type: 'Hash160', value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv' }, - { type: 'Integer', value: '100000000' }, - { type: 'Array', value: [] }, + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + { + type: 'Hash160', + value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv', + }, + { + type: 'Integer', + value: '100000000', + }, + { + type: 'Array', + value: [], + }, ], }, ], @@ -108,10 +125,22 @@ function HelloWorld() { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'transfer', args: [ - { type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }, - { type: 'Hash160', value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv' }, - { type: 'Integer', value: '100000000' }, - { type: 'Array', value: [] }, + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + { + type: 'Hash160', + value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv', + }, + { + type: 'Integer', + value: '100000000', + }, + { + type: 'Array', + value: [], + }, ], }, ], @@ -129,10 +158,22 @@ function HelloWorld() { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'transfer', args: [ - { type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }, - { type: 'Hash160', value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv' }, - { type: 'Integer', value: '100000000' }, - { type: 'Array', value: [] }, + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + { + type: 'Hash160', + value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv', + }, + { + type: 'Integer', + value: '100000000', + }, + { + type: 'Array', + value: [], + }, ], }, ], @@ -158,10 +199,22 @@ function HelloWorld() { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'transfer', args: [ - { type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }, - { type: 'Hash160', value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv' }, - { type: 'Integer', value: '100000000' }, - { type: 'Array', value: [] }, + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + { + type: 'Hash160', + value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv', + }, + { + type: 'Integer', + value: '100000000', + }, + { + type: 'Array', + value: [], + }, ], abortOnFail: true, }, @@ -175,7 +228,10 @@ function HelloWorld() { const signAndVerify = async (): Promise => { if (!wcSdk) return - const resp = await wcSdk.signMessage({ message: 'Your sign message', version: SignMessageVersion.DEFAULT }) + const resp = await wcSdk.signMessage({ + message: 'Your sign message', + version: SignMessageVersion.DEFAULT, + }) console.log(resp) setResponse(JSON.stringify(resp, null, 2)) @@ -188,7 +244,10 @@ function HelloWorld() { const signWithoutSaltAndVerify = async (): Promise => { if (!wcSdk) return - const resp = await wcSdk.signMessage({ message: 'Your sign message', version: SignMessageVersion.WITHOUT_SALT }) + const resp = await wcSdk.signMessage({ + message: 'Your sign message', + version: SignMessageVersion.WITHOUT_SALT, + }) console.log(resp) setResponse(JSON.stringify(resp, null, 2)) @@ -287,7 +346,10 @@ function HelloWorld() { } const signMessageEncryptAndDecrypt = async () => { - const signedMessage = await wcSdk.signMessage({ message: 'Message to Sign', version: SignMessageVersion.DEFAULT }) + const signedMessage = await wcSdk.signMessage({ + message: 'Message to Sign', + version: SignMessageVersion.DEFAULT, + }) const message = 'message to encrypt' const publicKeys = [signedMessage.publicKey] @@ -322,10 +384,22 @@ function HelloWorld() { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'transfer', args: [ - { type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }, - { type: 'Hash160', value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv' }, - { type: 'Integer', value: '100000000' }, - { type: 'Array', value: [] }, + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + { + type: 'Hash160', + value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv', + }, + { + type: 'Integer', + value: '100000000', + }, + { + type: 'Array', + value: [], + }, ], }, ], diff --git a/examples/wc-dapp-vite-vanilla/main.js b/examples/wc-dapp-vite-vanilla/main.js index 8aa3544..2a59def 100644 --- a/examples/wc-dapp-vite-vanilla/main.js +++ b/examples/wc-dapp-vite-vanilla/main.js @@ -55,7 +55,12 @@ const getMyBalance = async () => { { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'balanceOf', - args: [{ type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }], + args: [ + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + ], }, ], signers: [{ scopes: 1 }], @@ -73,10 +78,22 @@ const transferGas = async () => { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'transfer', args: [ - { type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }, - { type: 'Hash160', value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv' }, - { type: 'Integer', value: 100000000 }, - { type: 'Array', value: [] }, + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + { + type: 'Hash160', + value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv', + }, + { + type: 'Integer', + value: 100000000, + }, + { + type: 'Array', + value: [], + }, ], }, ], @@ -96,10 +113,22 @@ const transferGasWithExtraFee = async () => { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'transfer', args: [ - { type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }, - { type: 'Hash160', value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv' }, - { type: 'Integer', value: 100000000 }, - { type: 'Array', value: [] }, + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + { + type: 'Hash160', + value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv', + }, + { + type: 'Integer', + value: 100000000, + }, + { + type: 'Array', + value: [], + }, ], }, ], @@ -126,10 +155,22 @@ const multiInvokeFailing = async () => { scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', operation: 'transfer', args: [ - { type: 'Hash160', value: wcSdk.getAccountAddress() ?? '' }, - { type: 'Hash160', value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv' }, - { type: 'Integer', value: 100000000 }, - { type: 'Array', value: [] }, + { + type: 'Hash160', + value: wcSdk.getAccountAddress() ?? '', + }, + { + type: 'Hash160', + value: 'NbnjKGMBJzJ6j5PHeYhjJDaQ5Vy5UYu4Fv', + }, + { + type: 'Integer', + value: 100000000, + }, + { + type: 'Array', + value: [], + }, ], abortOnFail: true, }, diff --git a/examples/wc-wallet-react/config-overrides.js b/examples/wc-wallet-react/config-overrides.js index eb75bc3..0e7c09f 100644 --- a/examples/wc-wallet-react/config-overrides.js +++ b/examples/wc-wallet-react/config-overrides.js @@ -4,12 +4,12 @@ module.exports = function override(config) { resolve: { fullySpecified: false, fallback: { - crypto: require.resolve("crypto-browserify"), - querystring: require.resolve("querystring-es3"), - stream: require.resolve("stream-browserify"), - events: require.resolve("events"), + crypto: require.resolve('crypto-browserify'), + querystring: require.resolve('querystring-es3'), + stream: require.resolve('stream-browserify'), + events: require.resolve('events'), }, }, - }); - return config; -}; + }) + return config +} diff --git a/examples/wc-wallet-react/images.d.ts b/examples/wc-wallet-react/images.d.ts index a58c5d8..3f287ea 100644 --- a/examples/wc-wallet-react/images.d.ts +++ b/examples/wc-wallet-react/images.d.ts @@ -1,7 +1,7 @@ -declare module "*.svg"; -declare module "*.png"; -declare module "*.jpg"; -declare module "*.jpeg"; -declare module "*.gif"; -declare module "*.bmp"; -declare module "*.tiff"; +declare module '*.svg' +declare module '*.png' +declare module '*.jpg' +declare module '*.jpeg' +declare module '*.gif' +declare module '*.bmp' +declare module '*.tiff' diff --git a/examples/wc-wallet-react/src/App.tsx b/examples/wc-wallet-react/src/App.tsx index 71c501b..9996d45 100644 --- a/examples/wc-wallet-react/src/App.tsx +++ b/examples/wc-wallet-react/src/App.tsx @@ -1,32 +1,30 @@ -import * as React from "react"; -import DefaultCard from "./components/DefaultCard"; -import RequestCard from "./components/RequestCard"; -import ProposalCard from "./components/ProposalCard"; -import { useWalletConnectWallet } from "@cityofzion/wallet-connect-sdk-wallet-react"; -import { CloseButton, Flex } from "@chakra-ui/react"; -import Header from "./components/Header"; -import { useAccountContext } from "./context/AccountContext"; -import AccountEntry from "./components/AccountEntry"; -import { useEffect, useState } from "react"; -import ConnectDapp from "./components/ConnectDapp"; -import { WalletConnectNeonAdapter } from "./helpers/WalletConnectNeonAdapter"; -import { TSessionAndTRequest } from "./types"; +import * as React from 'react' +import DefaultCard from './components/DefaultCard' +import RequestCard from './components/RequestCard' +import ProposalCard from './components/ProposalCard' +import { useWalletConnectWallet } from '@cityofzion/wallet-connect-sdk-wallet-react' +import { CloseButton, Flex } from '@chakra-ui/react' +import Header from './components/Header' +import { useAccountContext } from './context/AccountContext' +import AccountEntry from './components/AccountEntry' +import { useEffect, useState } from 'react' +import ConnectDapp from './components/ConnectDapp' +import { WalletConnectNeonAdapter } from './helpers/WalletConnectNeonAdapter' +import { TSessionAndTRequest } from './types' export default function App(): any { - const walletConnectCtx = useWalletConnectWallet(); - const accountCtx = useAccountContext(); - const [connectingApp, setConnectingApp] = useState(false); - const [requestOpen, setRequestOpen] = useState(undefined); + const walletConnectCtx = useWalletConnectWallet() + const accountCtx = useAccountContext() + const [connectingApp, setConnectingApp] = useState(false) + const [requestOpen, setRequestOpen] = useState(undefined) useEffect(() => { - setConnectingApp(!walletConnectCtx.sessions.length); - }, [walletConnectCtx.sessions]); + setConnectingApp(!walletConnectCtx.sessions.length) + }, [walletConnectCtx.sessions]) useEffect(() => { - walletConnectCtx.setAdapter( - new WalletConnectNeonAdapter(accountCtx.rpcAddress, accountCtx.account), - ); - }, [accountCtx.rpcAddress, accountCtx.account]); + walletConnectCtx.setAdapter(new WalletConnectNeonAdapter(accountCtx.rpcAddress, accountCtx.account)) + }, [accountCtx.rpcAddress, accountCtx.account]) return ( @@ -36,24 +34,15 @@ export default function App(): any { ) : walletConnectCtx.proposals.length ? ( ) : requestOpen ? ( - setRequestOpen(undefined)} - flex={1} - /> + setRequestOpen(undefined)} flex={1} /> ) : connectingApp ? ( - {!!walletConnectCtx.sessions.length && ( - setConnectingApp(false)} /> - )} + {!!walletConnectCtx.sessions.length && setConnectingApp(false)} />} ) : ( - setRequestOpen(e)} - openConnectingDapp={() => setConnectingApp(true)} - /> + setRequestOpen(e)} openConnectingDapp={() => setConnectingApp(true)} /> )} - ); + ) } diff --git a/examples/wc-wallet-react/src/components/AccountEntry.tsx b/examples/wc-wallet-react/src/components/AccountEntry.tsx index f2fd4e1..2257ee4 100644 --- a/examples/wc-wallet-react/src/components/AccountEntry.tsx +++ b/examples/wc-wallet-react/src/components/AccountEntry.tsx @@ -1,4 +1,4 @@ -import * as React from "react"; +import * as React from 'react' import { Box, Button, @@ -11,89 +11,89 @@ import { Spinner, Text, useToast, -} from "@chakra-ui/react"; -import { FileHelper } from "../helpers/FileHelper"; -import { useCallback, useEffect, useState } from "react"; -import { wallet } from "@cityofzion/neon-core"; -import { useAccountContext } from "../context/AccountContext"; -import { DEFAULT_NETWORKS } from "../constants"; +} from '@chakra-ui/react' +import { FileHelper } from '../helpers/FileHelper' +import { useCallback, useEffect, useState } from 'react' +import { wallet } from '@cityofzion/neon-core' +import { useAccountContext } from '../context/AccountContext' +import { DEFAULT_NETWORKS } from '../constants' export default function AccountEntry(props: DividerProps): any { - const accountCtx = useAccountContext(); - const toast = useToast(); - const [choseNetwork, setChoseNetwork] = useState(false); - const [creatingNew, setCreatingNew] = useState(false); - const [loading, setLoading] = useState(false); + const accountCtx = useAccountContext() + const toast = useToast() + const [choseNetwork, setChoseNetwork] = useState(false) + const [creatingNew, setCreatingNew] = useState(false) + const [loading, setLoading] = useState(false) const setAccount = (acc: wallet.Account) => { - accountCtx.setAccount(acc); - }; + accountCtx.setAccount(acc) + } const loadAccountFromStorage = useCallback(async () => { if (!accountCtx.account) { - const str = localStorage.getItem("account"); - const json = str ? (JSON.parse(str) as Partial) : null; + const str = localStorage.getItem('account') + const json = str ? (JSON.parse(str) as Partial) : null if (json) { - const account = new wallet.Account(json); - setAccount(account); + const account = new wallet.Account(json) + setAccount(account) } } - }, [accountCtx]); + }, [accountCtx]) useEffect(() => { - loadAccountFromStorage(); - }, [loadAccountFromStorage]); + loadAccountFromStorage() + }, [loadAccountFromStorage]) const login = async (e: React.SyntheticEvent) => { - e.preventDefault(); - setLoading(true); - await passwordOnAccount(); - setLoading(false); - }; + e.preventDefault() + setLoading(true) + await passwordOnAccount() + setLoading(false) + } const passwordOnAccount = async () => { if (accountCtx.account && accountCtx.accountPassword) { if (!creatingNew) { try { - await accountCtx.account.decrypt(accountCtx.accountPassword); + await accountCtx.account.decrypt(accountCtx.accountPassword) } catch (e: any) { toast({ title: e.message, - status: "error", + status: 'error', duration: 3000, isClosable: true, - }); - return; + }) + return } } - accountCtx.setAccountDecripted(true); + accountCtx.setAccountDecripted(true) try { - await accountCtx.account.encrypt(accountCtx.accountPassword); + await accountCtx.account.encrypt(accountCtx.accountPassword) } catch (e) { - console.log("error encrypting account"); + console.log('error encrypting account') } - await localStorage.setItem("account", JSON.stringify(accountCtx.account.export())); + await localStorage.setItem('account', JSON.stringify(accountCtx.account.export())) } - }; + } const importAccount = async () => { - const file = await FileHelper.promptForSingleFile("json"); - const json = await file?.text(); + const file = await FileHelper.promptForSingleFile('json') + const json = await file?.text() if (json) { - const acc = JSON.parse(json); - const account = new wallet.Account(acc); - setAccount(account); - setCreatingNew(false); + const acc = JSON.parse(json) + const account = new wallet.Account(acc) + setAccount(account) + setCreatingNew(false) } - }; + } const createAccount = async () => { - const account = new wallet.Account(); - setAccount(account); - setCreatingNew(true); - }; + const account = new wallet.Account() + setAccount(account) + setCreatingNew(true) + } return ( @@ -127,7 +127,7 @@ export default function AccountEntry(props: DividerProps): any { ))} - {accountCtx.networkType === "private" && ( + {accountCtx.networkType === 'private' && ( <> RPC Address @@ -138,7 +138,7 @@ export default function AccountEntry(props: DividerProps): any { borderColor="#373d4a" borderRadius={0} bg="#1a202b" - _placeholder={{ color: "#373d4a" }} + _placeholder={{ color: '#373d4a' }} mt="0.5rem" w="20rem" /> @@ -151,7 +151,7 @@ export default function AccountEntry(props: DividerProps): any { mt="1.5rem" bg="#373d4a" borderRadius={0} - _hover={{ bg: "black" }} + _hover={{ bg: 'black' }} > Continue @@ -162,13 +162,7 @@ export default function AccountEntry(props: DividerProps): any { Do you have an Account JSON File? - @@ -228,14 +222,7 @@ export default function AccountEntry(props: DividerProps): any { - {!creatingNew && ( @@ -245,7 +232,7 @@ export default function AccountEntry(props: DividerProps): any { h="2.75rem" bg="#373d4a" borderRadius={0} - _hover={{ bg: "black" }} + _hover={{ bg: 'black' }} mt="0.5rem" > Generate a new Account @@ -256,5 +243,5 @@ export default function AccountEntry(props: DividerProps): any { )} - ); + ) } diff --git a/examples/wc-wallet-react/src/components/ConnectDapp.tsx b/examples/wc-wallet-react/src/components/ConnectDapp.tsx index b497342..31a54fa 100644 --- a/examples/wc-wallet-react/src/components/ConnectDapp.tsx +++ b/examples/wc-wallet-react/src/components/ConnectDapp.tsx @@ -1,103 +1,93 @@ -import * as React from "react"; -import { - Box, - Button, - DividerProps, - Flex, - Input, - Spacer, - Spinner, - Text, - useToast, -} from "@chakra-ui/react"; -import { useCallback, useEffect, useState } from "react"; -import Scanner, { ScannerValidation } from "./Scanner"; -import { useWalletConnectWallet } from "@cityofzion/wallet-connect-sdk-wallet-react"; +import * as React from 'react' +import { Box, Button, DividerProps, Flex, Input, Spacer, Spinner, Text, useToast } from '@chakra-ui/react' +import { useCallback, useEffect, useState } from 'react' +import Scanner, { ScannerValidation } from './Scanner' +import { useWalletConnectWallet } from '@cityofzion/wallet-connect-sdk-wallet-react' export default function ConnectDapp(props: DividerProps): any { - const walletConnectCtx = useWalletConnectWallet(); - const toast = useToast(); - const [scanner, setScanner] = useState(false); - const [loading, setLoading] = useState(false); + const walletConnectCtx = useWalletConnectWallet() + const toast = useToast() + const [scanner, setScanner] = useState(false) + const [loading, setLoading] = useState(false) const handleScan = () => { - setLoading(true); - setScanner(true); - }; + setLoading(true) + setScanner(true) + } const handleInput = async (e: any) => { - setLoading(true); + setLoading(true) try { - await walletConnectCtx.connect(e.target.value.trim()); + await walletConnectCtx.connect(e.target.value.trim()) } catch (e) { - setLoading(false); + setLoading(false) toast({ - title: "Invalid input", - status: "error", + title: 'Invalid input', + status: 'error', duration: 3000, isClosable: true, - }); + }) } - }; + } const onScannerValidate = (data: string) => { - const res: ScannerValidation = { error: null, result: null }; + const res: ScannerValidation = { error: null, result: null } try { - res.result = data; + res.result = data } catch (error: any) { - res.error = error; + res.error = error } - return res; - }; + return res + } const onScannerScan = async (data: any) => { - await walletConnectCtx.connect(data); - setScanner(false); - }; + await walletConnectCtx.connect(data) + setScanner(false) + } const onScannerError = (error: Error) => { - setLoading(false); + setLoading(false) toast({ title: error.message, - status: "error", + status: 'error', duration: 3000, isClosable: true, - }); - }; + }) + } const closeScanner = () => { - setScanner(false); - setLoading(false); - }; + setScanner(false) + setLoading(false) + } useEffect(() => { - setLoading(false); - }, [walletConnectCtx.proposals.length]); + setLoading(false) + }, [walletConnectCtx.proposals.length]) const handleUnhandledRejection = useCallback( (event: PromiseRejectionEvent) => { - if (event.reason.message && event.reason.message.includes("No matching pairing")) { - setLoading(false); + if (event.reason.message && event.reason.message.includes('No matching pairing')) { + setLoading(false) toast({ - title: "Expired code", - status: "error", + title: 'Expired code', + status: 'error', duration: 3000, isClosable: true, - }); - event.preventDefault(); + }) + event.preventDefault() } }, [toast], - ); + ) useEffect(() => { - window.addEventListener("unhandledrejection", handleUnhandledRejection); + window.addEventListener('unhandledrejection', handleUnhandledRejection) return () => { - window.removeEventListener("unhandledrejection", handleUnhandledRejection); - }; - }, [handleUnhandledRejection]); + window.removeEventListener('unhandledrejection', handleUnhandledRejection) + } + }, [handleUnhandledRejection]) return ( @@ -109,14 +99,7 @@ export default function ConnectDapp(props: DividerProps): any { Connect with an App - @@ -133,7 +116,7 @@ export default function ConnectDapp(props: DividerProps): any { data-testid="connect-dapp__dapp-uri-input" maxW="20rem" bg="#1a202b" - _placeholder={{ color: "#373d4a" }} + _placeholder={{ color: '#373d4a' }} mt="2rem" placeholder="Paste the Code " /> @@ -149,5 +132,5 @@ export default function ConnectDapp(props: DividerProps): any { /> )} - ); + ) } diff --git a/examples/wc-wallet-react/src/components/DefaultCard.tsx b/examples/wc-wallet-react/src/components/DefaultCard.tsx index 53a4a4d..44645ed 100644 --- a/examples/wc-wallet-react/src/components/DefaultCard.tsx +++ b/examples/wc-wallet-react/src/components/DefaultCard.tsx @@ -1,26 +1,26 @@ -import * as React from "react"; -import { MotionProps } from "framer-motion"; +import * as React from 'react' +import { MotionProps } from 'framer-motion' -import { Button, ChakraProps, DividerProps, Flex, Link, Spacer, Text } from "@chakra-ui/react"; -import { useWalletConnectWallet } from "@cityofzion/wallet-connect-sdk-wallet-react"; -import Peer from "../components/Peer"; -import { DeleteIcon } from "@chakra-ui/icons"; -import { TSessionAndTRequest } from "../types"; +import { Button, ChakraProps, DividerProps, Flex, Link, Spacer, Text } from '@chakra-ui/react' +import { useWalletConnectWallet } from '@cityofzion/wallet-connect-sdk-wallet-react' +import Peer from '../components/Peer' +import { DeleteIcon } from '@chakra-ui/icons' +import { TSessionAndTRequest } from '../types' export type MotionBoxProps = Omit & MotionProps & { - as?: React.ElementType; - }; + as?: React.ElementType + } export default function DefaultCard( props: DividerProps & { - openConnectingDapp: () => any; - openRequest: (request: TSessionAndTRequest) => any; + openConnectingDapp: () => any + openRequest: (request: TSessionAndTRequest) => any }, ): any { - const walletConnectCtx = useWalletConnectWallet(); + const walletConnectCtx = useWalletConnectWallet() - const { openConnectingDapp, openRequest, ...dividerProps } = props; + const { openConnectingDapp, openRequest, ...dividerProps } = props return ( @@ -30,14 +30,14 @@ export default function DefaultCard( bg="#373d4a" borderRadius={0} mt="1.5rem" - _hover={{ bg: "black" }} + _hover={{ bg: 'black' }} onClick={openConnectingDapp} > Make a new Connection - {"Sessions"} + {'Sessions'} {walletConnectCtx.sessions.map((session) => ( Pending Request: - {" "} + {' '} {requestEvent.params.request.method} ), @@ -85,5 +85,5 @@ export default function DefaultCard( ))} - ); + ) } diff --git a/examples/wc-wallet-react/src/components/Header.tsx b/examples/wc-wallet-react/src/components/Header.tsx index 70edf0c..02f67b0 100644 --- a/examples/wc-wallet-react/src/components/Header.tsx +++ b/examples/wc-wallet-react/src/components/Header.tsx @@ -1,65 +1,65 @@ -import * as React from "react"; -import { Flex, Image, Link, Text } from "@chakra-ui/react"; -import LogoutIcon from "./icon/LogoutIcon"; -import { FileHelper } from "../helpers/FileHelper"; -import { useAccountContext } from "../context/AccountContext"; -import { useCallback, useEffect, useState } from "react"; -import { NeonInvoker, NeonParser } from "@cityofzion/neon-dappkit"; +import * as React from 'react' +import { Flex, Image, Link, Text } from '@chakra-ui/react' +import LogoutIcon from './icon/LogoutIcon' +import { FileHelper } from '../helpers/FileHelper' +import { useAccountContext } from '../context/AccountContext' +import { useCallback, useEffect, useState } from 'react' +import { NeonInvoker, NeonParser } from '@cityofzion/neon-dappkit' const chainMeta = { - name: "Neo3", - logo: "https://cryptologos.cc/logos/neo-neo-logo.svg", -}; + name: 'Neo3', + logo: 'https://cryptologos.cc/logos/neo-neo-logo.svg', +} export default function Header(): any { - const accountCtx = useAccountContext(); - const [balance, setBalance] = useState(); + const accountCtx = useAccountContext() + const [balance, setBalance] = useState() const logout = async () => { - accountCtx.setAccountPassword(undefined); - accountCtx.setAccountDecripted(false); - }; + accountCtx.setAccountPassword(undefined) + accountCtx.setAccountDecripted(false) + } - const ellipseAddress = (address = "", width = 10) => { - return `${address.slice(0, width)}...${address.slice(-width)}`; - }; + const ellipseAddress = (address = '', width = 10) => { + return `${address.slice(0, width)}...${address.slice(-width)}` + } const exportAccount = async () => { - const json = accountCtx.account?.export(); - FileHelper.downloadJsonFile(accountCtx.account?.address ?? "", json); - }; + const json = accountCtx.account?.export() + FileHelper.downloadJsonFile(accountCtx.account?.address ?? '', json) + } const isLoggedIn = () => { - return accountCtx.account && accountCtx.accountDecripted; - }; + return accountCtx.account && accountCtx.accountDecripted + } const loadBalance = useCallback(async () => { if (!accountCtx.account) { - return undefined; + return undefined } const invoker = await NeonInvoker.init({ rpcAddress: accountCtx.rpcAddress, - }); + }) const response = await invoker.testInvoke({ invocations: [ { - operation: "balanceOf", - scriptHash: "0xd2a4cff31913016155e38e474a2c06d08be276cf", - args: [{ value: accountCtx.account.address, type: "Hash160" }], + operation: 'balanceOf', + scriptHash: '0xd2a4cff31913016155e38e474a2c06d08be276cf', + args: [{ value: accountCtx.account.address, type: 'Hash160' }], }, ], - }); + }) - const gas = NeonParser.parseRpcResponse(response.stack[0]) / Math.pow(10, 8); + const gas = NeonParser.parseRpcResponse(response.stack[0]) / Math.pow(10, 8) - setBalance(gas); - }, [accountCtx.account, accountCtx.networkType, accountCtx.privateRpcAddress]); + setBalance(gas) + }, [accountCtx.account, accountCtx.networkType, accountCtx.privateRpcAddress]) useEffect(() => { - loadBalance(); - }, [loadBalance]); + loadBalance() + }, [loadBalance]) return ( - + Web Wallet @@ -82,13 +82,7 @@ export default function Header(): any { {accountCtx.account && ( - {chainMeta.name} + {chainMeta.name} {ellipseAddress(accountCtx.account.address, 8)} @@ -106,5 +100,5 @@ export default function Header(): any { )} - ); + ) } diff --git a/examples/wc-wallet-react/src/components/Peer.tsx b/examples/wc-wallet-react/src/components/Peer.tsx index 31da77c..1c53423 100644 --- a/examples/wc-wallet-react/src/components/Peer.tsx +++ b/examples/wc-wallet-react/src/components/Peer.tsx @@ -1,6 +1,6 @@ -import * as React from "react"; -import { SignClientTypes } from "@walletconnect/types"; -import { Flex, Image, Text, Link, Spacer, DividerProps } from "@chakra-ui/react"; +import * as React from 'react' +import { SignClientTypes } from '@walletconnect/types' +import { Flex, Image, Text, Link, Spacer, DividerProps } from '@chakra-ui/react' export default function Peer(props: { metadata: SignClientTypes.Metadata } & DividerProps): any { return ( @@ -17,5 +17,5 @@ export default function Peer(props: { metadata: SignClientTypes.Metadata } & Div - ); + ) } diff --git a/examples/wc-wallet-react/src/components/ProposalCard.tsx b/examples/wc-wallet-react/src/components/ProposalCard.tsx index f7dcb1d..a8dd590 100644 --- a/examples/wc-wallet-react/src/components/ProposalCard.tsx +++ b/examples/wc-wallet-react/src/components/ProposalCard.tsx @@ -1,19 +1,19 @@ -import * as React from "react"; -import Peer from "../components/Peer"; -import { Button, DividerProps, Flex, Spacer, Text } from "@chakra-ui/react"; -import { useAccountContext } from "../context/AccountContext"; -import { useWalletConnectWallet } from "@cityofzion/wallet-connect-sdk-wallet-react"; +import * as React from 'react' +import Peer from '../components/Peer' +import { Button, DividerProps, Flex, Spacer, Text } from '@chakra-ui/react' +import { useAccountContext } from '../context/AccountContext' +import { useWalletConnectWallet } from '@cityofzion/wallet-connect-sdk-wallet-react' export default function ProposalCard(props: DividerProps): any { - const walletConnectCtx = useWalletConnectWallet(); - const accountCtx = useAccountContext(); - const firstProposal = walletConnectCtx.proposals[0]; + const walletConnectCtx = useWalletConnectWallet() + const accountCtx = useAccountContext() + const firstProposal = walletConnectCtx.proposals[0] const approveSession = async () => { await walletConnectCtx.approveProposal(firstProposal, { - account: { address: accountCtx.account?.address ?? "", chain: accountCtx.networkType }, - }); - }; + account: { address: accountCtx.account?.address ?? '', chain: accountCtx.networkType }, + }) + } return ( @@ -21,13 +21,7 @@ export default function ProposalCard(props: DividerProps): any { {!!walletConnectCtx.proposals.length && ( - + {JSON.stringify(firstProposal.params.requiredNamespaces, null, 2)} @@ -37,7 +31,7 @@ export default function ProposalCard(props: DividerProps): any { data-testid="proposal-card__approve" bg="black" borderRadius={0} - _hover={{ bg: "#111" }} + _hover={{ bg: '#111' }} > Approve @@ -46,7 +40,7 @@ export default function ProposalCard(props: DividerProps): any { onClick={() => walletConnectCtx.rejectProposal(firstProposal)} bg="black" borderRadius={0} - _hover={{ bg: "#111" }} + _hover={{ bg: '#111' }} ml="0.5rem" > Reject @@ -56,5 +50,5 @@ export default function ProposalCard(props: DividerProps): any { )} - ); + ) } diff --git a/examples/wc-wallet-react/src/components/RequestCard.tsx b/examples/wc-wallet-react/src/components/RequestCard.tsx index 701c6b8..c044dd0 100644 --- a/examples/wc-wallet-react/src/components/RequestCard.tsx +++ b/examples/wc-wallet-react/src/components/RequestCard.tsx @@ -1,49 +1,47 @@ -import * as React from "react"; +import * as React from 'react' -import Peer from "../components/Peer"; -import { Button, Spinner, DividerProps, Flex, Image, Spacer, Text, Box } from "@chakra-ui/react"; -import { useState } from "react"; -import { useWalletConnectWallet } from "@cityofzion/wallet-connect-sdk-wallet-react"; -import { TSessionAndTRequest } from "../types"; +import Peer from '../components/Peer' +import { Button, Spinner, DividerProps, Flex, Image, Spacer, Text, Box } from '@chakra-ui/react' +import { useState } from 'react' +import { useWalletConnectWallet } from '@cityofzion/wallet-connect-sdk-wallet-react' +import { TSessionAndTRequest } from '../types' export default function RequestCard( props: DividerProps & { sessionAndRequest: TSessionAndTRequest; closeRequest: () => void }, ): any { - const walletConnectCtx = useWalletConnectWallet(); - const [sendingResponse, setSendingResponse] = useState(false); + const walletConnectCtx = useWalletConnectWallet() + const [sendingResponse, setSendingResponse] = useState(false) - const request = props.sessionAndRequest.request.params.request; + const request = props.sessionAndRequest.request.params.request const approve = async () => { - setSendingResponse(true); + setSendingResponse(true) try { - await walletConnectCtx.approveRequest(props.sessionAndRequest.request); + await walletConnectCtx.approveRequest(props.sessionAndRequest.request) } finally { - setSendingResponse(false); - props.closeRequest(); + setSendingResponse(false) + props.closeRequest() } - }; + } const reject = async () => { - setSendingResponse(true); - await walletConnectCtx.rejectRequest(props.sessionAndRequest.request); - setSendingResponse(false); - props.closeRequest(); - }; + setSendingResponse(true) + await walletConnectCtx.rejectRequest(props.sessionAndRequest.request) + setSendingResponse(false) + props.closeRequest() + } const items = Array.isArray(request.params) ? request.params : request.params.invocations ? request.params.invocations - : [request.params]; + : [request.params] return ( - {props.sessionAndRequest.session.peer && ( - - )} + {props.sessionAndRequest.session.peer && } ( - + {i.toString(10)} - - {typeof p === "object" ? "" : typeof p === "number" ? p + 1 : p.toString()} - + {typeof p === 'object' ? '' : typeof p === 'number' ? p + 1 : p.toString()} - {typeof p === "object" && ( + {typeof p === 'object' && ( {Object.keys(p).map((k: string) => ( - {p[k] && - (typeof p[k] !== "object" ? p[k].toString() : JSON.stringify(p[k]))} + {p[k] && (typeof p[k] !== 'object' ? p[k].toString() : JSON.stringify(p[k]))} ))} @@ -128,7 +113,7 @@ export default function RequestCard( data-testid="request-card__approve" bg="black" borderRadius={0} - _hover={{ bg: "#111" }} + _hover={{ bg: '#111' }} > Approve @@ -138,7 +123,7 @@ export default function RequestCard( data-testid="request-card__reject" bg="black" borderRadius={0} - _hover={{ bg: "#111" }} + _hover={{ bg: '#111' }} ml="0.5rem" > Reject @@ -148,5 +133,5 @@ export default function RequestCard( - ); + ) } diff --git a/examples/wc-wallet-react/src/components/Scanner.tsx b/examples/wc-wallet-react/src/components/Scanner.tsx index 1de71de..afbfaf5 100644 --- a/examples/wc-wallet-react/src/components/Scanner.tsx +++ b/examples/wc-wallet-react/src/components/Scanner.tsx @@ -1,6 +1,6 @@ -import * as React from "react"; -import styled from "styled-components"; -import QrReader from "react-qr-reader"; +import * as React from 'react' +import styled from 'styled-components' +import QrReader from 'react-qr-reader' const SScannerContainer = styled.div` position: fixed; @@ -11,7 +11,7 @@ const SScannerContainer = styled.div` z-index: 5; margin: 0 auto !important; background: rgb(0, 0, 0); -`; +` const SScannerWrapper = styled.div` position: relative; @@ -23,7 +23,7 @@ const SScannerWrapper = styled.div` flex-direction: column; align-items: center; justify-content: center; -`; +` const SCloseButton = styled.div` transition: all 0.2s ease-in-out; @@ -40,72 +40,72 @@ const SCloseButton = styled.div` &:hover { opacity: 0.5; } -`; +` const SFirstLine = styled.div` position: absolute; width: 90%; border: 1px solid rgb(255, 255, 255); -`; +` const SSecondLine = styled(SFirstLine as any)` transform: rotate(90deg); -`; +` export interface ScannerValidation { - error: Error | null; - result: any | null; + error: Error | null + result: any | null } interface ScannerProps { - onValidate: (data: string) => ScannerValidation; - onScan: (data: any) => void; - onError: (error: Error) => void; - onClose: () => void; + onValidate: (data: string) => ScannerValidation + onScan: (data: any) => void + onError: (error: Error) => void + onClose: () => void } interface ScannerState { - delay: number | false; + delay: number | false } class Scanner extends React.Component { public state = { delay: 300, - }; + } public stopRecording: () => Promise = async () => { - await this.setState({ delay: false }); - }; + await this.setState({ delay: false }) + } public handleScan: (data: string | null) => void = (data: string | null) => { if (data) { - const { result, error } = this.props.onValidate(data); + const { result, error } = this.props.onValidate(data) if (result) { - this.stopRecording(); - this.props.onScan(result); + this.stopRecording() + this.props.onScan(result) } else { - this.handleError(error); + this.handleError(error) } } - }; + } public handleError: (error: Error | null) => void = (error: Error | null) => { if (error) { - this.props.onError(error); + this.props.onError(error) } - }; + } public onClose: () => Promise = async () => { try { - await this.stopRecording(); - this.props.onClose(); + await this.stopRecording() + this.props.onClose() } catch (error: any) { - this.handleError(error); + this.handleError(error) } - }; + } public componentWillUnmount(): void { - this.stopRecording(); + this.stopRecording() } public render(): any { @@ -120,12 +120,12 @@ class Scanner extends React.Component { delay={this.state.delay} onError={this.handleError} onScan={this.handleScan} - style={{ width: "100%" }} + style={{ width: '100%' }} /> - ); + ) } } -export default Scanner; +export default Scanner diff --git a/examples/wc-wallet-react/src/components/icon/LogoutIcon.tsx b/examples/wc-wallet-react/src/components/icon/LogoutIcon.tsx index dc29238..8eb1d96 100644 --- a/examples/wc-wallet-react/src/components/icon/LogoutIcon.tsx +++ b/examples/wc-wallet-react/src/components/icon/LogoutIcon.tsx @@ -1,5 +1,5 @@ -import { Icon } from "@chakra-ui/react"; -import { FunctionComponent } from "react"; +import { Icon } from '@chakra-ui/react' +import { FunctionComponent } from 'react' const LogoutIcon: FunctionComponent = (props: any) => ( @@ -24,6 +24,6 @@ const LogoutIcon: FunctionComponent = (props: any) => ( d="m282.667969 448.007812h-85.335938c-8.832031 0-16-7.167968-16-16 0-8.832031 7.167969-16 16-16h85.335938c14.699219 0 26.664062-11.96875 26.664062-26.667968v-96c0-8.832032 7.167969-16 16-16s16 7.167968 16 16v96c0 32.363281-26.300781 58.667968-58.664062 58.667968zm0 0" /> -); +) -export default LogoutIcon; +export default LogoutIcon diff --git a/examples/wc-wallet-react/src/constants/default.ts b/examples/wc-wallet-react/src/constants/default.ts index 201c3f4..abbcded 100644 --- a/examples/wc-wallet-react/src/constants/default.ts +++ b/examples/wc-wallet-react/src/constants/default.ts @@ -1,39 +1,39 @@ -import { Chain, Method } from "@cityofzion/wallet-connect-sdk-wallet-react"; +import { Chain, Method } from '@cityofzion/wallet-connect-sdk-wallet-react' -export const DEFAULT_RELAY_PROVIDER = "wss://relay.walletconnect.com"; +export const DEFAULT_RELAY_PROVIDER = 'wss://relay.walletconnect.com' -export const DEFAULT_PROJECT_ID = "56de852a69580b46d61b53f7b3922ce1"; +export const DEFAULT_PROJECT_ID = '56de852a69580b46d61b53f7b3922ce1' export const DEFAULT_METHODS: Method[] = [ - "invokeFunction", - "testInvoke", - "signMessage", - "verifyMessage", - "getWalletInfo", - "traverseIterator", - "getNetworkVersion", - "decrypt", - "encrypt", - "decryptFromArray", - "calculateFee", - "signTransaction", -]; + 'invokeFunction', + 'testInvoke', + 'signMessage', + 'verifyMessage', + 'getWalletInfo', + 'traverseIterator', + 'getNetworkVersion', + 'decrypt', + 'encrypt', + 'decryptFromArray', + 'calculateFee', + 'signTransaction', +] -export const DEFAULT_LOGGER = "error"; +export const DEFAULT_LOGGER = 'error' export const DEFAULT_APP_METADATA = { - name: "CoZ Wallet Prototype", - description: "WalletConnect integration Prototype", - url: "https://coz.io/", + name: 'CoZ Wallet Prototype', + description: 'WalletConnect integration Prototype', + url: 'https://coz.io/', icons: [ - "https://raw.githubusercontent.com/CityOfZion/visual-identity/develop/_CoZ%20Branding/_Logo/_Logo%20icon/_PNG%20200x178px/CoZ_Icon_DARKBLUE_200x178px.png", + 'https://raw.githubusercontent.com/CityOfZion/visual-identity/develop/_CoZ%20Branding/_Logo/_Logo%20icon/_PNG%20200x178px/CoZ_Icon_DARKBLUE_200x178px.png', ], -}; +} -export const DEFAULT_CHAIN: Chain = "testnet"; +export const DEFAULT_CHAIN: Chain = 'testnet' export const DEFAULT_NETWORKS: Record = { - testnet: { url: "https://testnet1.neo.coz.io:443", name: "Testnet" }, - mainnet: { url: "http://seed1.neo.org:10332", name: "Mainnet" }, - private: { url: null, name: "Private Network" }, -}; -export const DEFAULT_BLOCKCHAINS = ["neo3"] as const; + testnet: { url: 'https://testnet1.neo.coz.io:443', name: 'Testnet' }, + mainnet: { url: 'http://seed1.neo.org:10332', name: 'Mainnet' }, + private: { url: null, name: 'Private Network' }, +} +export const DEFAULT_BLOCKCHAINS = ['neo3'] as const diff --git a/examples/wc-wallet-react/src/constants/index.ts b/examples/wc-wallet-react/src/constants/index.ts index f348fd4..a17c69c 100644 --- a/examples/wc-wallet-react/src/constants/index.ts +++ b/examples/wc-wallet-react/src/constants/index.ts @@ -1 +1 @@ -export * from "./default"; +export * from './default' diff --git a/examples/wc-wallet-react/src/context/AccountContext.tsx b/examples/wc-wallet-react/src/context/AccountContext.tsx index 6e6472a..7adcc6c 100644 --- a/examples/wc-wallet-react/src/context/AccountContext.tsx +++ b/examples/wc-wallet-react/src/context/AccountContext.tsx @@ -1,34 +1,34 @@ -import React, { useContext, useMemo, useState } from "react"; -import { Account } from "@cityofzion/neon-core/lib/wallet"; -import { DEFAULT_CHAIN, DEFAULT_NETWORKS } from "../constants"; -import { Chain } from "@cityofzion/wallet-connect-sdk-wallet-react"; +import React, { useContext, useMemo, useState } from 'react' +import { Account } from '@cityofzion/neon-core/lib/wallet' +import { DEFAULT_CHAIN, DEFAULT_NETWORKS } from '../constants' +import { Chain } from '@cityofzion/wallet-connect-sdk-wallet-react' interface IAccountContext { - accountPassword: string | undefined; - setAccountPassword: React.Dispatch>; - accountDecripted: boolean; - setAccountDecripted: React.Dispatch>; - privateRpcAddress: string; - setPrivateRpcAddress: React.Dispatch>; - networkType: Chain; - setNetworkType: React.Dispatch>; - account: Account | undefined; - setAccount: React.Dispatch>; - rpcAddress: string; + accountPassword: string | undefined + setAccountPassword: React.Dispatch> + accountDecripted: boolean + setAccountDecripted: React.Dispatch> + privateRpcAddress: string + setPrivateRpcAddress: React.Dispatch> + networkType: Chain + setNetworkType: React.Dispatch> + account: Account | undefined + setAccount: React.Dispatch> + rpcAddress: string } -export const AccountContext = React.createContext({} as IAccountContext); +export const AccountContext = React.createContext({} as IAccountContext) export const AccountContextProvider: React.FC = ({ children }) => { - const [accountPassword, setAccountPassword] = useState(undefined); - const [accountDecripted, setAccountDecripted] = useState(false); - const [networkType, setNetworkType] = useState(DEFAULT_CHAIN); - const [privateRpcAddress, setPrivateRpcAddress] = useState("http://localhost"); - const [account, setAccount] = useState(); + const [accountPassword, setAccountPassword] = useState(undefined) + const [accountDecripted, setAccountDecripted] = useState(false) + const [networkType, setNetworkType] = useState(DEFAULT_CHAIN) + const [privateRpcAddress, setPrivateRpcAddress] = useState('http://localhost') + const [account, setAccount] = useState() const rpcAddress = useMemo(() => { - return DEFAULT_NETWORKS[networkType].url || privateRpcAddress; - }, [networkType, privateRpcAddress]); + return DEFAULT_NETWORKS[networkType].url || privateRpcAddress + }, [networkType, privateRpcAddress]) const contextValue: IAccountContext = { accountPassword, @@ -42,9 +42,9 @@ export const AccountContextProvider: React.FC = ({ children }) => { account, setAccount, rpcAddress, - }; + } - return {children}; -}; + return {children} +} -export const useAccountContext = (): IAccountContext => useContext(AccountContext); +export const useAccountContext = (): IAccountContext => useContext(AccountContext) diff --git a/examples/wc-wallet-react/src/helpers/FileHelper.ts b/examples/wc-wallet-react/src/helpers/FileHelper.ts index 2101e2c..d050964 100644 --- a/examples/wc-wallet-react/src/helpers/FileHelper.ts +++ b/examples/wc-wallet-react/src/helpers/FileHelper.ts @@ -1,141 +1,138 @@ export abstract class FileHelper { static fileOrBlobToArrBuffer(file: File | Blob): Promise { return new Promise((resolve) => { - const reader = new FileReader(); + const reader = new FileReader() reader.onload = () => { - resolve(reader.result as ArrayBuffer); - }; + resolve(reader.result as ArrayBuffer) + } - reader.readAsArrayBuffer(file); - }); + reader.readAsArrayBuffer(file) + }) } static async fileToArrBuffer(file: File): Promise { - return await this.fileOrBlobToArrBuffer(file); + return await this.fileOrBlobToArrBuffer(file) } static async blobToArrBuffer(blob: Blob): Promise { - return await this.fileOrBlobToArrBuffer(blob); + return await this.fileOrBlobToArrBuffer(blob) } static fileToUrl(file: File | Blob): Promise { return new Promise((resolve) => { - const reader = new FileReader(); + const reader = new FileReader() reader.onload = () => { - resolve(reader.result as string); - }; - reader.readAsDataURL(file); - }); + resolve(reader.result as string) + } + reader.readAsDataURL(file) + }) } static urlToImg(url: string): Promise { return new Promise((resolve) => { - const img = new Image(); + const img = new Image() img.onload = () => { - resolve(img); - }; + resolve(img) + } - img.src = url; - }); + img.src = url + }) } static canvasToBlob(canvas: HTMLCanvasElement): Promise { return new Promise((resolve) => { canvas.toBlob((blob: Blob | null) => { - resolve(blob); - }); - }); + resolve(blob) + }) + }) } static urlToBlob(dataURI: string): Blob { - let byteString: string; - if (dataURI.split(",")[0].indexOf("base64") >= 0) { - byteString = atob(dataURI.split(",")[1]); + let byteString: string + if (dataURI.split(',')[0].indexOf('base64') >= 0) { + byteString = atob(dataURI.split(',')[1]) } else { - byteString = unescape(dataURI.split(",")[1]); + byteString = unescape(dataURI.split(',')[1]) } // separate out the mime component - const mimeString: string = dataURI.split(",")[0].split(":")[1].split(";")[0]; + const mimeString: string = dataURI.split(',')[0].split(':')[1].split(';')[0] // write the bytes of the string to a typed array - const ia = new Uint8Array(byteString.length); + const ia = new Uint8Array(byteString.length) for (let i = 0; i < byteString.length; i++) { - ia[i] = byteString.charCodeAt(i); + ia[i] = byteString.charCodeAt(i) } - return new Blob([ia], { type: mimeString }); + return new Blob([ia], { type: mimeString }) } static urlToArrayBuffer(dataURI: string): Promise { - const blob = this.urlToBlob(dataURI); - return this.fileOrBlobToArrBuffer(blob); + const blob = this.urlToBlob(dataURI) + return this.fileOrBlobToArrBuffer(blob) } static async fileToImg(file: File | Blob): Promise { - const url = await this.fileToUrl(file); - return await this.urlToImg(url); + const url = await this.fileToUrl(file) + return await this.urlToImg(url) } static fileOrBlobToExtension(file: Blob | File): string { - return file.type.includes("jpeg") ? "jpg" : file.type.split("/")[1]; + return file.type.includes('jpeg') ? 'jpg' : file.type.split('/')[1] } static arrayBufferToBlob(arrayBuffer: ArrayBuffer): Blob { - return new Blob([arrayBuffer], { type: "image/jpeg" }); + return new Blob([arrayBuffer], { type: 'image/jpeg' }) } static blobToUrl(blob: Blob): string { - return (window.URL || window.webkitURL).createObjectURL(blob); + return (window.URL || window.webkitURL).createObjectURL(blob) } static arrayBufferToUrl(arrayBuffer: ArrayBuffer): string { - const blob = this.arrayBufferToBlob(arrayBuffer); - return this.blobToUrl(blob); + const blob = this.arrayBufferToBlob(arrayBuffer) + return this.blobToUrl(blob) } - static promptForMultipleFiles( - accept: string | null = null, - multiple = true, - ): Promise { + static promptForMultipleFiles(accept: string | null = null, multiple = true): Promise { return new Promise((resolve) => { - const input = document.createElement("input"); - input.type = "file"; + const input = document.createElement('input') + input.type = 'file' if (accept) { - input.accept = accept; + input.accept = accept } if (multiple) { - input.setAttribute("multiple", "multiple"); + input.setAttribute('multiple', 'multiple') } - document.body.appendChild(input); + document.body.appendChild(input) input.onchange = (e: any) => { - document.body.removeChild(input); - resolve(e.target.files); - }; + document.body.removeChild(input) + resolve(e.target.files) + } - input.click(); - }); + input.click() + }) } static async promptForSingleFile(accept: string | null = null): Promise { - const files: File[] | null = await this.promptForMultipleFiles(accept, false); + const files: File[] | null = await this.promptForMultipleFiles(accept, false) if (!files || !files.length) { - return null; + return null } - return files[0]; + return files[0] } static downloadJsonFile(name: string, obj: unknown): void { - const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj)); - const downloadAnchorNode = document.createElement("a"); - downloadAnchorNode.setAttribute("href", dataStr); - downloadAnchorNode.setAttribute("download", name + ".json"); - document.body.appendChild(downloadAnchorNode); - downloadAnchorNode.click(); - downloadAnchorNode.remove(); + const dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(obj)) + const downloadAnchorNode = document.createElement('a') + downloadAnchorNode.setAttribute('href', dataStr) + downloadAnchorNode.setAttribute('download', name + '.json') + document.body.appendChild(downloadAnchorNode) + downloadAnchorNode.click() + downloadAnchorNode.remove() } } diff --git a/examples/wc-wallet-react/src/helpers/WalletConnectNeonAdapter.ts b/examples/wc-wallet-react/src/helpers/WalletConnectNeonAdapter.ts index e6dfed2..65d8a6e 100644 --- a/examples/wc-wallet-react/src/helpers/WalletConnectNeonAdapter.ts +++ b/examples/wc-wallet-react/src/helpers/WalletConnectNeonAdapter.ts @@ -1,26 +1,23 @@ -import { - AbstractWalletConnectNeonAdapter, - WalletInfo, -} from "@cityofzion/wallet-connect-sdk-wallet-react"; -import { Account } from "@cityofzion/neon-core/lib/wallet"; +import { AbstractWalletConnectNeonAdapter, WalletInfo } from '@cityofzion/wallet-connect-sdk-wallet-react' +import { Account } from '@cityofzion/neon-core/lib/wallet' export class WalletConnectNeonAdapter extends AbstractWalletConnectNeonAdapter { constructor( public rpcAddress: string | undefined = undefined, public account: Account | undefined = undefined, ) { - super(); + super() } async getAccountString(): Promise { - return this.account?.WIF ?? ""; + return this.account?.WIF ?? '' } async getRPCUrl(): Promise { - return this.rpcAddress ?? "https://testnet2.neo.coz.io:443"; + return this.rpcAddress ?? 'https://testnet2.neo.coz.io:443' } async getWalletInfo(): Promise { - return { isLedger: false }; + return { isLedger: false } } } diff --git a/examples/wc-wallet-react/src/index.tsx b/examples/wc-wallet-react/src/index.tsx index 7cf1b5f..eb93572 100644 --- a/examples/wc-wallet-react/src/index.tsx +++ b/examples/wc-wallet-react/src/index.tsx @@ -1,16 +1,16 @@ -import * as React from "react"; -import * as ReactDOM from "react-dom"; -import { ChakraProvider } from "@chakra-ui/react"; +import * as React from 'react' +import * as ReactDOM from 'react-dom' +import { ChakraProvider } from '@chakra-ui/react' import { DEFAULT_APP_METADATA, DEFAULT_LOGGER, DEFAULT_RELAY_PROVIDER, DEFAULT_PROJECT_ID, DEFAULT_METHODS, -} from "./constants"; -import App from "./App"; -import { WalletConnectWalletProvider } from "@cityofzion/wallet-connect-sdk-wallet-react"; -import { AccountContextProvider } from "./context/AccountContext"; +} from './constants' +import App from './App' +import { WalletConnectWalletProvider } from '@cityofzion/wallet-connect-sdk-wallet-react' +import { AccountContextProvider } from './context/AccountContext' const wcOptions = { clientOptions: { @@ -20,7 +20,7 @@ const wcOptions = { relayUrl: DEFAULT_RELAY_PROVIDER, }, methods: DEFAULT_METHODS, -}; +} ReactDOM.render( <> @@ -32,5 +32,5 @@ ReactDOM.render( , - document.getElementById("root"), -); + document.getElementById('root'), +) diff --git a/examples/wc-wallet-react/src/types.ts b/examples/wc-wallet-react/src/types.ts index 6b3d4c3..c9fc99b 100644 --- a/examples/wc-wallet-react/src/types.ts +++ b/examples/wc-wallet-react/src/types.ts @@ -1,6 +1,6 @@ -import { TSession, TSessionRequest } from "@cityofzion/wallet-connect-sdk-wallet-react"; +import { TSession, TSessionRequest } from '@cityofzion/wallet-connect-sdk-wallet-react' export type TSessionAndTRequest = { - session: TSession; - request: TSessionRequest; -}; + session: TSession + request: TSessionRequest +} diff --git a/packages/wallet-connect-sdk-core/src/index.ts b/packages/wallet-connect-sdk-core/src/index.ts index da607ae..59825fc 100644 --- a/packages/wallet-connect-sdk-core/src/index.ts +++ b/packages/wallet-connect-sdk-core/src/index.ts @@ -235,7 +235,10 @@ export default class WcSdk implements Neo3Invoker, Neo3Signer { async createConnection( network: NetworkType, methods: Method[], - ): Promise<{ uri?: string; approval: () => Promise }> { + ): Promise<{ + uri?: string + approval: () => Promise + }> { if (methods === undefined) { console.warn(defaultMethodRemovedWarning) methods = ['invokeFunction', 'testInvoke', 'signMessage', 'verifyMessage'] @@ -267,7 +270,10 @@ export default class WcSdk implements Neo3Invoker, Neo3Signer { await this.signClient.disconnect({ topic: this.session.topic, - reason: { code: 5900, message: 'USER_DISCONNECTED' }, + reason: { + code: 5900, + message: 'USER_DISCONNECTED', + }, }) this.session = null diff --git a/packages/wallet-connect-sdk-react/src/index.tsx b/packages/wallet-connect-sdk-react/src/index.tsx index 62ca382..3067b32 100644 --- a/packages/wallet-connect-sdk-react/src/index.tsx +++ b/packages/wallet-connect-sdk-react/src/index.tsx @@ -75,7 +75,10 @@ interface IWalletConnectContext extends Neo3Invoker, Neo3Signer { createConnection: ( network: NetworkType, methods: Method[], - ) => Promise<{ uri?: string; approval: () => Promise }> + ) => Promise<{ + uri?: string + approval: () => Promise + }> /** * disconnects from the wallet @@ -178,7 +181,10 @@ export const WalletConnectProvider: React.FC<{ async ( network: NetworkType, methods: Method[], - ): Promise<{ uri?: string; approval: () => Promise }> => { + ): Promise<{ + uri?: string + approval: () => Promise + }> => { return await getSdkOrError().createConnection(network, methods) }, [getSdkOrError], diff --git a/packages/wallet-connect-sdk-wallet-core/src/sdk.ts b/packages/wallet-connect-sdk-wallet-core/src/sdk.ts index c04ac84..4bb9189 100644 --- a/packages/wallet-connect-sdk-wallet-core/src/sdk.ts +++ b/packages/wallet-connect-sdk-wallet-core/src/sdk.ts @@ -212,7 +212,9 @@ export class WcWalletSDK { if (!wccv) throw new Error('Invalid URI') if (wccv > COMPATIBILITY_VERSION) throw new Error('Incompatible WCCV. Update your wallet to use new features.') - const { topic } = await this.signClient.pair({ uri }) + const { topic } = await this.signClient.pair({ + uri, + }) this.wccvs.set(topic, wccv) } @@ -225,7 +227,10 @@ export class WcWalletSDK { public async disconnect(session: TSession, reason?: TRejectReason): Promise { await this.signClient.disconnect({ topic: session.topic, - reason: reason ?? { code: 5900, message: 'USER_DISCONNECTED' }, + reason: reason ?? { + code: 5900, + message: 'USER_DISCONNECTED', + }, }) const filtered = this.sessions.filter(({ topic }) => session.topic !== topic) @@ -263,7 +268,11 @@ export class WcWalletSDK { const wccv = this.wccvs.get(session.pairingTopic) if (!wccv) throw new Error('WCCV not set') - const extendedSession = { ...session, approvalUnix, wccv } + const extendedSession = { + ...session, + approvalUnix, + wccv, + } this.sessions = [...this.sessions, extendedSession] return extendedSession diff --git a/packages/wallet-connect-sdk-wallet-core/src/types.ts b/packages/wallet-connect-sdk-wallet-core/src/types.ts index 551cfca..2421afb 100644 --- a/packages/wallet-connect-sdk-wallet-core/src/types.ts +++ b/packages/wallet-connect-sdk-wallet-core/src/types.ts @@ -33,7 +33,10 @@ export type TOptions = { } export type TApproveSessionOptions = { - account: { address: string; chain: Chain } + account: { + address: string + chain: Chain + } } export type TSessionExtendedStorage = { diff --git a/prettier.config.js b/prettier.config.js deleted file mode 100644 index 02b3c22..0000000 --- a/prettier.config.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - singleQuote: true, - arrowParens: 'avoid', - bracketSpacing: true, - printWidth: 120, - semi: false, - tabWidth: 2, - useTabs: false, - trailingComma: 'es5', -}