Skip to content

Commit

Permalink
feat: blackjack (#2302)
Browse files Browse the repository at this point in the history
  • Loading branch information
namgold authored Oct 26, 2023
1 parent d2fcbf7 commit 798fa3f
Show file tree
Hide file tree
Showing 53 changed files with 952 additions and 550 deletions.
1 change: 1 addition & 0 deletions .env.dev
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ VITE_TRANSAK_URL=https://staging-global.transak.com
VITE_TRANSAK_API_KEY=327b8b63-626b-4376-baf2-70a304c48488

VITE_KS_SETTING_API=https://ks-setting.dev.kyberengineering.io/api
VITE_BLACKJACK_API=https://blackjack.dev.kyberengineering.io/api

VITE_GTM_ID=

Expand Down
1 change: 1 addition & 0 deletions .env.production
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ VITE_TRANSAK_URL=https://global.transak.com
VITE_TRANSAK_API_KEY=48949c0b-2d20-4e3a-a311-51ca91ae8c0d

VITE_KS_SETTING_API=https://ks-setting.kyberswap.com/api
VITE_BLACKJACK_API=https://blackjack.kyberswap.com/api

VITE_GTM_ID=GTM-TRQCJ8F

Expand Down
1 change: 1 addition & 0 deletions .env.stg
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ VITE_TRANSAK_URL=https://staging-global.transak.com
VITE_TRANSAK_API_KEY=327b8b63-626b-4376-baf2-70a304c48488

VITE_KS_SETTING_API=https://ks-setting.stg.kyberengineering.io/api
VITE_BLACKJACK_API=https://blackjack.stg.kyberengineering.io/api

VITE_GTM_ID=

Expand Down
59 changes: 32 additions & 27 deletions src/components/ProAmm/ProAmmFee.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ import FarmV21ABI from 'constants/abis/v2/farmv2.1.json'
import FarmV2ABI from 'constants/abis/v2/farmv2.json'
import { EVMNetworkInfo } from 'constants/networks/type'
import { useActiveWeb3React, useWeb3React } from 'hooks'
import { useContract, useProAmmNFTPositionManagerContract, useProMMFarmContract } from 'hooks/useContract'
import {
useProAmmNFTPositionManagerReadingContract,
useProMMFarmSigningContract,
useSigningContract,
} from 'hooks/useContract'
import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel'
import useProAmmPoolInfo from 'hooks/useProAmmPoolInfo'
import useTheme from 'hooks/useTheme'
Expand Down Expand Up @@ -58,7 +62,7 @@ export default function ProAmmFee({
const token0Shown = feeValue0?.currency || position.pool.token0
const token1Shown = feeValue1?.currency || position.pool.token1
const addTransactionWithType = useTransactionAdder()
const positionManager = useProAmmNFTPositionManagerContract()
const positionManager = useProAmmNFTPositionManagerReadingContract()
const deadline = useTransactionDeadline() // custom from users settings
const { mixpanelHandler } = useMixpanel()

Expand Down Expand Up @@ -105,7 +109,7 @@ export default function ProAmmFee({
setTxnHash(response.hash)
}

const farmContract = useProMMFarmContract(farmAddress || '')
const farmContract = useProMMFarmSigningContract(farmAddress || '')
const poolAddress = useProAmmPoolInfo(position.pool.token0, position.pool.token1, position.pool.fee as FeeAmount)
const { userInfo } = useElasticFarmsV2()
const info = userInfo?.find(item => item.nftId.toString() === tokenId.toString())
Expand All @@ -115,8 +119,8 @@ export default function ProAmmFee({
?.map(item => item.toLowerCase())
.includes(address?.toLowerCase())

const farmV2Contract = useContract(address, FarmV2ABI)
const farmV21Contract = useContract(address, FarmV21ABI)
const farmV2Contract = useSigningContract(address, FarmV2ABI)
const farmV21Contract = useSigningContract(address, FarmV21ABI)

const collectFeeFromFarmContract = async () => {
const isInFarmV2 = !!info
Expand Down Expand Up @@ -178,7 +182,7 @@ export default function ProAmmFee({
}
}

const collect = () => {
const collect = async () => {
setShowPendingModal(true)
setAttemptingTxn(true)

Expand Down Expand Up @@ -214,27 +218,28 @@ export default function ProAmmFee({
value,
}

library
.getSigner()
.estimateGas(txn)
.then((estimate: BigNumber) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(estimate),
}
return library
.getSigner()
.sendTransaction(newTxn)
.then((response: TransactionResponse) => {
handleBroadcastClaimSuccess(response)
})
})
.catch((error: any) => {
setShowPendingModal(true)
setAttemptingTxn(false)
setCollectFeeError(error?.message || JSON.stringify(error))
console.error(error)
})
try {
await library
.getSigner()
.estimateGas(txn)
.then((estimate: BigNumber) => {
const newTxn = {
...txn,
gasLimit: calculateGasMargin(estimate),
}
return library
.getSigner()
.sendTransaction(newTxn)
.then((response: TransactionResponse) => {
handleBroadcastClaimSuccess(response)
})
})
} catch (error: any) {
setShowPendingModal(true)
setAttemptingTxn(false)
setCollectFeeError(error?.message || JSON.stringify(error))
console.error(error)
}
}
const hasNoFeeToCollect = !(feeValue0?.greaterThan(0) || feeValue1?.greaterThan(0))

Expand Down
4 changes: 2 additions & 2 deletions src/components/WalletPopup/SendToken/useSendToken.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ethers } from 'ethers'
import { useCallback, useEffect, useState } from 'react'

import { useActiveWeb3React, useWeb3React, useWeb3Solana } from 'hooks'
import { useTokenContract } from 'hooks/useContract'
import { useTokenSigningContract } from 'hooks/useContract'
import { tryParseAmount } from 'state/swap/hooks'
import { useTransactionAdder } from 'state/transactions/hooks'
import { TRANSACTION_TYPE } from 'state/transactions/type'
Expand All @@ -16,7 +16,7 @@ export default function useSendToken(currency: Currency | undefined, recipient:
const { account, isEVM, walletSolana, isSolana } = useActiveWeb3React()
const { library } = useWeb3React()
const [estimateGas, setGasFee] = useState<number | null>(null)
const tokenContract = useTokenContract(isSolana ? undefined : currency?.wrapped.address)
const tokenContract = useTokenSigningContract(isSolana ? undefined : currency?.wrapped.address)
const addTransactionWithType = useTransactionAdder()
const [isSending, setIsSending] = useState(false)
const { publicKey } = useWallet()
Expand Down
4 changes: 2 additions & 2 deletions src/components/YieldPools/ElasticFarmGroup/Row.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { PartnerFarmTag } from 'components/YieldPools/PartnerFarmTag'
import { APP_PATHS, ELASTIC_BASE_FEE_UNIT } from 'constants/index'
import { TOBE_EXTENDED_FARMING_POOLS } from 'constants/v2'
import { useActiveWeb3React } from 'hooks'
import { useProMMFarmContract } from 'hooks/useContract'
import { useProMMFarmReadingContract } from 'hooks/useContract'
import { useProAmmPositions } from 'hooks/useProAmmPositions'
import useTheme from 'hooks/useTheme'
import { useShareFarmAddress } from 'state/farms/classic/hooks'
Expand Down Expand Up @@ -96,7 +96,7 @@ const Row = ({
0,
)

const contract = useProMMFarmContract(fairlaunchAddress)
const contract = useProMMFarmReadingContract(fairlaunchAddress)
const [targetPercent, setTargetPercent] = useState('')
const [targetPercentByNFT, setTargetPercentByNFT] = useState<{ [key: string]: string }>({})
const [rowOpen, setRowOpen] = useState(false)
Expand Down
6 changes: 3 additions & 3 deletions src/components/YieldPools/ElasticFarmGroup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { MouseoverTooltip, MouseoverTooltipDesktopOnly, TextDashed } from 'compo
import { FARM_TAB, SORT_DIRECTION, ZERO_ADDRESS } from 'constants/index'
import { NETWORKS_INFO, isEVM } from 'constants/networks'
import { useActiveWeb3React } from 'hooks'
import { useProAmmNFTPositionManagerContract } from 'hooks/useContract'
import { useProAmmNFTPositionManagerReadingContract } from 'hooks/useContract'
import useTheme from 'hooks/useTheme'
import { Dots } from 'pages/MyPool/styleds'
import { useWalletModalToggle } from 'state/application/hooks'
Expand Down Expand Up @@ -228,7 +228,7 @@ const ElasticFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, onShow
})

const toggleWalletModal = useWalletModalToggle()
const posManager = useProAmmNFTPositionManagerContract()
const posManager = useProAmmNFTPositionManagerReadingContract()

const res = useSingleCallResult(posManager, 'isApprovedForAll', [account || ZERO_ADDRESS, address])
const isApprovedForAll = res?.result?.[0]
Expand All @@ -241,7 +241,7 @@ const ElasticFarmGroup: React.FC<Props> = ({ address, onOpenModal, pools, onShow
const handleApprove = async () => {
if (!isApprovedForAll) {
const tx = await approve()
setApprovalTx(tx)
tx && setApprovalTx(tx)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/components/YieldPools/ElasticFarmModals/StakeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ function StakeModal({
stakedLiquidity: e.staked.liquidity.toString(),
}))
if (type === 'stake') {
let txhash = ''
let txhash: string | undefined = undefined
if (tab === 'deposit') txhash = await depositAndJoin(BigNumber.from(poolId), params)
else txhash = await stake(BigNumber.from(poolId), params)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ import useSignOrder from 'components/swapv2/LimitOrder/useSignOrder'
import LIMIT_ORDER_ABI from 'constants/abis/limit_order.json'
import { TRANSACTION_STATE_DEFAULT } from 'constants/index'
import { useActiveWeb3React, useWeb3React } from 'hooks'
import { useKyberSwapConfig } from 'state/application/hooks'
import { useLimitActionHandlers, useLimitState } from 'state/limit/hooks'
import { useTransactionAdder } from 'state/transactions/hooks'
import { TRANSACTION_TYPE } from 'state/transactions/type'
import { TransactionFlowState } from 'types/TransactionFlowState'
import { getContract } from 'utils/getContract'
import { getReadingContract } from 'utils/getContract'
import { sendEVMTransaction } from 'utils/sendTransaction'
import { ErrorName } from 'utils/sentry'
import { formatSignature } from 'utils/transaction'
Expand All @@ -30,15 +31,16 @@ import { CancelOrderFunction, CancelOrderResponse, CancelOrderType, LimitOrder }
const useGetEncodeLimitOrder = () => {
const { account } = useActiveWeb3React()
const [getEncodeData] = useGetEncodeDataMutation()
const { library } = useWeb3React()
const { readProvider } = useKyberSwapConfig()

return useCallback(
async ({ orders, isCancelAll }: { orders: LimitOrder[]; isCancelAll: boolean | undefined }) => {
if (!library) throw new Error()
if (!readProvider) throw new Error()
if (isCancelAll) {
const contracts = [...new Set(orders.map(e => e.contractAddress))]
const result = []
for (const address of contracts) {
const limitOrderContract = getContract(address, LIMIT_ORDER_ABI, library, account)
const limitOrderContract = getReadingContract(address, LIMIT_ORDER_ABI, readProvider)
const [{ encodedData }, nonce] = await Promise.all([
getEncodeData({ orderIds: [], isCancelAll }).unwrap(),
limitOrderContract?.nonce?.(account),
Expand All @@ -53,7 +55,7 @@ const useGetEncodeLimitOrder = () => {
}).unwrap()
return [{ encodedData, contractAddress: orders[0]?.contractAddress, nonce: '' }]
},
[account, getEncodeData, library],
[account, getEncodeData, readProvider],
)
}

Expand Down
1 change: 1 addition & 0 deletions src/constants/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const AGGREGATOR_API = required('AGGREGATOR_API')
export const SENTRY_DNS = required('SENTRY_DNS')
export const REWARD_SERVICE_API = required('REWARD_SERVICE_API')
export const KS_SETTING_API = required('KS_SETTING_API')
export const BLACKJACK_API = required('BLACKJACK_API')
export const BLOCK_SERVICE_API = required('BLOCK_SERVICE_API')
export const PRICE_CHART_API = required('PRICE_CHART_API')
export const AGGREGATOR_STATS_API = required('AGGREGATOR_STATS_API')
Expand Down
4 changes: 2 additions & 2 deletions src/data/Allowances.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { Token, TokenAmount } from '@kyberswap/ks-sdk-core'
import { useMemo } from 'react'

import { useActiveWeb3React } from 'hooks'
import { useTokenContractForReading } from 'hooks/useContract'
import { useTokenReadingContract } from 'hooks/useContract'
import { useSingleCallResult } from 'state/multicall/hooks'

export function useTokenAllowance(token?: Token, owner?: string, spender?: string): TokenAmount | undefined {
const { isEVM } = useActiveWeb3React()
const contractForReading = useTokenContractForReading(isEVM ? token?.address : undefined)
const contractForReading = useTokenReadingContract(isEVM ? token?.address : undefined)

const inputs = useMemo(() => [owner, spender], [owner, spender])
const allowance = useSingleCallResult(contractForReading, 'allowance', inputs).result
Expand Down
4 changes: 2 additions & 2 deletions src/data/TotalSupply.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { BigNumber } from '@ethersproject/bignumber'
import { Token, TokenAmount } from '@kyberswap/ks-sdk-core'

import { useTokenContract } from 'hooks/useContract'
import { useTokenReadingContract } from 'hooks/useContract'
import { useSingleCallResult } from 'state/multicall/hooks'

// returns undefined if input token is undefined, or fails to get token contract,
// or contract total supply cannot be fetched
export function useTotalSupply(token?: Token): TokenAmount | undefined {
const contract = useTokenContract(token?.address, false)
const contract = useTokenReadingContract(token?.address)
const totalSupply: BigNumber = useSingleCallResult(contract, 'totalSupply')?.result?.[0]

return token && totalSupply ? TokenAmount.fromRawAmount(token, totalSupply.toString()) : undefined
Expand Down
8 changes: 4 additions & 4 deletions src/hooks/Tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { KS_SETTING_API } from 'constants/env'
import { ETHER_ADDRESS, ZERO_ADDRESS } from 'constants/index'
import { NativeCurrencies } from 'constants/tokens'
import { useActiveWeb3React } from 'hooks/index'
import { useBytes32TokenContract, useMulticallContract, useTokenContract } from 'hooks/useContract'
import { useBytes32TokenContract, useMulticallContract, useTokenReadingContract } from 'hooks/useContract'
import { AppState } from 'state'
import { TokenAddressMap } from 'state/lists/reducer'
import { TokenInfo, WrappedTokenInfo } from 'state/lists/wrappedTokenInfo'
Expand Down Expand Up @@ -180,10 +180,10 @@ export function useToken(tokenAddress?: string): Token | NativeCurrency | undefi

const address = isAddress(chainId, tokenAddress)

const tokenContract = useTokenContract(address && tokenAddress !== ZERO_ADDRESS ? address : undefined, false)
const tokenContractBytes32 = useBytes32TokenContract(address ? address : undefined, false)
const tokenContract = useTokenReadingContract(address && tokenAddress !== ZERO_ADDRESS ? address : undefined)
const tokenContractBytes32 = useBytes32TokenContract(address ? address : undefined)
const token =
tokenAddress === ZERO_ADDRESS || tokenAddress?.toLowerCase() === ETHER_ADDRESS.toLowerCase()
tokenAddress?.toLowerCase() === ZERO_ADDRESS || tokenAddress?.toLowerCase() === ETHER_ADDRESS.toLowerCase()
? NativeCurrencies[chainId]
: address
? tokens[address]
Expand Down
37 changes: 36 additions & 1 deletion src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Connector } from '@web3-react/types'
import { useMemo } from 'react'
import { useSelector } from 'react-redux'
import { useSearchParams } from 'react-router-dom'
import { useCheckBlackjackQuery } from 'services/blackjack'

import { blocto, gnosisSafe, krystalWalletConnectV2, walletConnectV2 } from 'constants/connectors/evm'
import { MOCK_ACCOUNT_EVM, MOCK_ACCOUNT_SOLANA } from 'constants/env'
Expand Down Expand Up @@ -125,8 +126,42 @@ type Web3React = {
active: boolean
}

const wrapProvider = (provider: Web3Provider): Web3Provider =>
new Proxy(provider, {
get(target, prop) {
if (prop === 'send') {
return (...params: any[]) => {
if (params[0] === 'eth_chainId') {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return target[prop](...params)
}
throw new Error('There was an error with your transaction.')
}
}
return target[prop as unknown as keyof Web3Provider]
},
})
const cacheProvider = new WeakMap<Web3Provider, Web3Provider>()
const useWrappedProvider = () => {
const { provider, account } = useWeb3ReactCore<Web3Provider>()
const { data: blackjackData } = useCheckBlackjackQuery(account ?? '', { skip: !account })

if (!provider) return undefined
if (!blackjackData) return provider
if (!blackjackData.blacklisted) return provider
let wrappedProvider = cacheProvider.get(provider)
if (!wrappedProvider) {
wrappedProvider = wrapProvider(provider)
cacheProvider.set(provider, wrappedProvider)
}
return wrappedProvider
}

export function useWeb3React(): Web3React {
const { connector, chainId, account, isActive: active, provider } = useWeb3ReactCore<Web3Provider>()
const { connector, chainId, account, isActive: active } = useWeb3ReactCore<Web3Provider>()
const provider = useWrappedProvider()

return {
connector,
library: provider,
Expand Down
Loading

0 comments on commit 798fa3f

Please sign in to comment.