Skip to content

Commit

Permalink
feat: Krystal walletconnect (#2246)
Browse files Browse the repository at this point in the history
  • Loading branch information
namgold authored Oct 3, 2023
1 parent 1200a14 commit 459ed22
Show file tree
Hide file tree
Showing 31 changed files with 304 additions and 170 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ jobs:
VITE_TAG: ${{ needs.prepare.outputs.image_tag }}
CURRENT_BRANCH: ${{ needs.prepare.outputs.current_branch }}
NODE_OPTIONS: '--max_old_space_size=4096'
run: yarn build-adpr
run: yarn build-prod

- name: Docker build and push
uses: docker/build-push-action@v2
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"@coinbase/wallet-sdk": "^3.0.4",
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
"@kybernetwork/oauth2": "1.0.0",
"@kyberswap/krystal-walletconnect-v2": "0.0.1",
"@kyberswap/ks-sdk-classic": "^1.0.3",
"@kyberswap/ks-sdk-core": "1.0.11",
"@kyberswap/ks-sdk-elastic": "^1.1.2",
Expand Down Expand Up @@ -207,4 +208,4 @@
"@lingui/core": "3.14.0",
"@lingui/conf": "3.16.0"
}
}
}
29 changes: 29 additions & 0 deletions patches/@walletconnect+ethereum-provider+2.8.1.patch

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions src/components/AddressInputPanel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,17 @@ const Input = styled.input<{ error?: boolean }>`
}
padding: 0px;
-webkit-appearance: textfield;
appearance: textfield;
::-webkit-search-decoration {
-webkit-appearance: none;
appearance: none;
}
::-webkit-outer-spin-button,
::-webkit-inner-spin-button {
-webkit-appearance: none;
appearance: none;
}
`

Expand Down
8 changes: 6 additions & 2 deletions src/components/Header/web3/WalletModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -442,8 +442,12 @@ export default function WalletModal() {
minHeight={false}
maxHeight={90}
maxWidth={600}
bypassScrollLock={walletView === WALLET_VIEWS.PENDING && ['WALLET_CONNECT'].includes(pendingWalletKey)}
bypassFocusLock={walletView === WALLET_VIEWS.PENDING && ['WALLET_CONNECT', 'BLOCTO'].includes(pendingWalletKey)}
bypassScrollLock={
walletView === WALLET_VIEWS.PENDING && ['WALLET_CONNECT', 'KRYSTAL_WC'].includes(pendingWalletKey)
}
bypassFocusLock={
walletView === WALLET_VIEWS.PENDING && ['WALLET_CONNECT', 'KRYSTAL_WC', 'BLOCTO'].includes(pendingWalletKey)
}
>
<Wrapper>{getModalContent()}</Wrapper>
</Modal>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Menu/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ export default function Menu() {
title={t`About`}
link={'/about'}
options={[
{ link: '/about/kyberswap', label: 'Kyberswap' },
{ link: '/about/kyberswap', label: 'KyberSwap' },
{ link: '/about/knc', label: 'KNC' },
]}
/>
Expand Down
12 changes: 6 additions & 6 deletions src/components/ProAmm/CandleStickChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import styled from 'styled-components'
import { PoolRatesEntry } from 'data/type'
import useTheme from 'hooks/useTheme'
import { useDarkModeManager } from 'state/user/hooks'
import { formatNotDollarAmount } from 'utils/numbers'
import { formatDisplayNumber } from 'utils/numbers'

const IconWrapper = styled.div`
position: absolute;
Expand Down Expand Up @@ -38,14 +38,14 @@ type CandleStickChartPropsType = {
}

const valueFormatter = (val: number) => {
let e: number
let fraction: number
if (val < 1.01 && val > 0.99) {
const leftover = Math.abs(val - 1)
e = parseInt(leftover.toExponential().match(/e([+-][0-9]+)/)?.[1] ?? '0')
fraction = parseInt(leftover.toExponential().match(/e([+-][0-9]+)/)?.[1] ?? '0')
} else {
e = parseInt(val.toExponential().match(/e([+-][0-9]+)/)?.[1] ?? '0')
fraction = parseInt(val.toExponential().match(/e([+-][0-9]+)/)?.[1] ?? '0')
}
return formatNotDollarAmount(val, 3 - e)
return formatDisplayNumber(val, { fractionDigits: 3 - fraction })
}

const CandleStickChart = ({
Expand Down Expand Up @@ -140,7 +140,7 @@ const CandleStickChart = ({
borderColor: 'rgba(197, 203, 206, 0.8)',
},
localization: {
priceFormatter: (val: number) => formatNotDollarAmount(val, 6),
priceFormatter: (val: number) => formatDisplayNumber(val, { significantDigits: 6, allowNegative: true }),
},
})

Expand Down
1 change: 1 addition & 0 deletions src/components/TransactionConfirmationModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ function AddTokenToInjectedWallet({ token, chainId }: { token: Token; chainId: C
if (!walletKey) return null
if (!isEVM) return null
if (walletKey === 'WALLET_CONNECT') return null
if (walletKey === 'KRYSTAL_WC') return null
const walletConfig = SUPPORTED_WALLETS[walletKey]

return (
Expand Down
8 changes: 6 additions & 2 deletions src/components/swapv2/LimitOrder/ListOrder/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
} from 'utils/firebase'
import { getContract } from 'utils/getContract'
import { sendEVMTransaction } from 'utils/sendTransaction'
import { ErrorName } from 'utils/sentry'

import EditOrderModal from '../EditOrderModal'
import CancelOrderModal from '../Modals/CancelOrderModal'
Expand Down Expand Up @@ -118,7 +119,7 @@ export const checkOrderActive = (order: LimitOrder) => {
}

export default forwardRef<ListOrderHandle>(function ListLimitOrder(props, ref) {
const { account, chainId, networkInfo } = useActiveWeb3React()
const { account, chainId, networkInfo, walletKey } = useActiveWeb3React()
const { library } = useWeb3React()
const [curPage, setCurPage] = useState(1)

Expand Down Expand Up @@ -293,7 +294,10 @@ export default forwardRef<ListOrderHandle>(function ListLimitOrder(props, ref) {
const newOrders = isCancelAll ? orders.map(e => e.id) : order?.id ? [order?.id] : []

const sendTransaction = async (encodedData: string, contract: string, payload: any) => {
const response = await sendEVMTransaction(account, library, contract, encodedData, BigNumber.from(0))
const response = await sendEVMTransaction(account, library, contract, encodedData, BigNumber.from(0), {
name: ErrorName.LimitOrderError,
wallet: walletKey,
})
if (response?.hash) {
insertCancellingOrder({
maker: account,
Expand Down
79 changes: 45 additions & 34 deletions src/constants/connectors/evm.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BloctoConnector } from '@blocto/web3-react-connector'
import { WalletConnect as KrystalWalletConnect } from '@kyberswap/krystal-walletconnect-v2'
import { ChainId } from '@kyberswap/ks-sdk-core'
import { OPTIONAL_EVENTS } from '@walletconnect/ethereum-provider'
import { CoinbaseWallet } from '@web3-react/coinbase-wallet'
Expand Down Expand Up @@ -35,43 +36,53 @@ export const [blocto, bloctoHooks] = initializeConnector<BloctoConnector>(
export const [bloctoInject, bloctoInjectHooks] = initializeConnector<MetaMask>(actions => new MetaMask({ actions }))

const darkmode = Boolean(window.matchMedia('(prefers-color-scheme: dark)'))
const walletconnectConfig = {
options: {
projectId: WALLETCONNECT_PROJECT_ID,
chains: WALLET_CONNECT_REQUIRED_CHAIN_IDS,
optionalChains: WALLET_CONNECT_OPTIONAL_CHAIN_IDS,
showQrModal: true,
methods: ['eth_sendTransaction', 'personal_sign', 'eth_signTypedData_v4'],
optionalMethods: ['eth_signTypedData', 'eth_sign'],
// optionalMethods: OPTIONAL_METHODS,
optionalEvents: OPTIONAL_EVENTS,
rpcMap: WALLET_CONNECT_SUPPORTED_CHAIN_IDS.reduce((acc, cur) => {
acc[cur] = NETWORKS_INFO[cur].defaultRpcUrl
return acc
}, {} as { [key in ChainId]: string }),
qrModalOptions: {
chainImages: undefined,
themeMode: darkmode ? ('dark' as const) : ('light' as const),
themeVariables: {
'--w3m-z-index': '1000',
'--w3m-logo-image-url': Kyber,
'--w3m-background-image-url': WC_BG,
'--w3m-accent-color': '#31CB9E',
'--w3m-accent-fill-color': '#222222',
'--w3m-color-bg-1': '#0F0F0F',
} as any,
},
metadata: {
name: 'KyberSwap',
description: document.title,
url: window.location.origin,
icons: ['https://kyberswap.com/favicon.svg'],
},
},
}

export const [walletConnectV2, walletConnectV2Hooks] = initializeConnector<WalletConnectV2>(
actions =>
new WalletConnectV2({
actions,
defaultChainId: ChainId.MAINNET,
options: {
projectId: WALLETCONNECT_PROJECT_ID,
chains: WALLET_CONNECT_REQUIRED_CHAIN_IDS,
optionalChains: WALLET_CONNECT_OPTIONAL_CHAIN_IDS,
showQrModal: true,
methods: ['eth_sendTransaction', 'personal_sign', 'eth_signTypedData_v4'],
optionalMethods: ['eth_signTypedData', 'eth_sign'],
// optionalMethods: OPTIONAL_METHODS,
optionalEvents: OPTIONAL_EVENTS,
rpcMap: WALLET_CONNECT_SUPPORTED_CHAIN_IDS.reduce((acc, cur) => {
acc[cur] = NETWORKS_INFO[cur].defaultRpcUrl
return acc
}, {} as { [key in ChainId]: string }),
qrModalOptions: {
chainImages: undefined,
themeMode: darkmode ? 'dark' : 'light',
themeVariables: {
'--w3m-z-index': '1000',
'--w3m-logo-image-url': Kyber,
'--w3m-background-image-url': WC_BG,
'--w3m-accent-color': '#31CB9E',
'--w3m-accent-fill-color': '#222222',
'--w3m-color-bg-1': '#0F0F0F',
} as any,
},
metadata: {
name: 'Kyberswap',
description: document.title,
url: window.location.origin,
icons: ['https://kyberswap.com/favicon.svg'],
},
},
...walletconnectConfig,
}),
)
export const [krystalWalletConnectV2, krystalWalletConnectV2Hooks] = initializeConnector<KrystalWalletConnect>(
actions =>
new KrystalWalletConnect({
actions,
...walletconnectConfig,
}),
)

Expand All @@ -81,7 +92,7 @@ export const [coinbaseWallet, coinbaseWalletHooks] = initializeConnector<Coinbas
actions,
options: {
url: NETWORKS_INFO[ChainId.MAINNET].defaultRpcUrl,
appName: 'Kyberswap',
appName: 'KyberSwap',
},
}),
)
44 changes: 35 additions & 9 deletions src/constants/connectors/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,32 @@ import checkForBraveBrowser from 'utils/checkForBraveBrowser'

if (ENV_LEVEL == ENV_TYPE.ADPR) {
setTimeout(() => {
console.log('capturing Injected window.ethereum', { level: 'info', extra: { 'window.ethereum': window.ethereum } })
captureMessage('Injected window.ethereum', { level: 'info', extra: { 'window.ethereum': window.ethereum } })
}, 2000)
if (getIsGenericInjector()) {
const params = {
level: 'warning',
extra: {
detector: {
isMetaMaskWallet: getIsMetaMaskWallet(),
isCoinbaseWallet: getIsCoinbaseWallet(),
isBraveWallet: getIsBraveWallet(),
isC98Wallet: getIsC98Wallet(),
isRabbyWallet: getIsRabbyWallet(),
isBloctoWallet: getIsBloctoWallet(),
isKrystalWallet: getIsKrystalWallet(),
isTrustWallet: getIsTrustWallet(),
isGenericInjector: getIsGenericInjector(),
},
'window.ethereum': window.ethereum,
'window.web3': window.web3,
'window.coin98': window.coin98,
'window.coinbaseWalletExtension': window.coinbaseWalletExtension,
'navigator.brave': navigator.brave,
},
} as const
captureMessage('Unknown injected window.ethereum', params)
console.info('Capturing injected window.ethereum', { params })
}
}, 5000)
}

export const getIsInjected = () => Boolean(window.ethereum)
Expand Down Expand Up @@ -78,12 +101,15 @@ export enum ErrorCode {
ALPHA_WALLET_REJECTED = 'Request rejected',
}

const rejectedPhrases: readonly string[] = [
'user rejected transaction',
'User declined to send the transaction',
'user denied transaction',
'you must accept',
].map(phrase => phrase.toLowerCase())
// Known phrases:
// - User declined to send the transaction ...
// - user denied transaction ...
// - user rejected transaction ...
// - User rejected methods ...
// - User rejected the request ...
const rejectedPhrases: readonly string[] = ['User declined', 'user denied', 'you must accept', 'User rejected'].map(
phrase => phrase.toLowerCase(),
)

export function didUserReject(error: any): boolean {
const message = String(
Expand Down
Loading

0 comments on commit 459ed22

Please sign in to comment.