Skip to content

Commit

Permalink
Merge pull request #457 from forbole/dev
Browse files Browse the repository at this point in the history
v0.13.1
  • Loading branch information
calvinkei committed Nov 28, 2021
2 parents e0fc83a + ec4e9a0 commit cc2defe
Show file tree
Hide file tree
Showing 13 changed files with 198 additions and 52 deletions.
2 changes: 1 addition & 1 deletion components/Banner/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const Banner: React.FC = () => {
}}
>
{banners.map((banner) => (
<Link href="/dsm-airdrop">
<Link href="/dsm-airdrop" key={banner}>
<CardMedia className={classes.bannerImage} image={banner} component="img" />
</Link>
))}
Expand Down
4 changes: 1 addition & 3 deletions components/ConfirmTransactionDialog/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,7 @@ const ConfirmTransactionDialog: React.FC<ConfirmTransactionDialogProps> = ({

React.useEffect(() => {
if (defaultTransactionData && account) {
estimateGasFee(defaultTransactionData, account).then((f) =>
setFee(granter ? { ...f, granter } : f)
)
estimateGasFee(defaultTransactionData, account, granter).then(setFee)
}
}, [defaultTransactionData, account, granter])

Expand Down
16 changes: 13 additions & 3 deletions components/ConnectLedgerDialogContent/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import React from 'react'
import Carousel from 'react-material-ui-carousel'
import TransportWebHID from '@ledgerhq/hw-transport-webhid'
import { LaunchpadLedger } from '@cosmjs/ledger-amino'
import TerraApp from '@terra-money/ledger-terra-js'
import LedgerImage from '../../assets/images/ledger.svg'
import LedgerSignImage from '../../assets/images/sign_ledger.svg'
import LedgerSignPinImage from '../../assets/images/sign_ledger_with_PIN.svg'
Expand Down Expand Up @@ -65,9 +66,18 @@ const ConnectLedgerDialogContent: React.FC<ConnectLedgerDialogContentProps> = ({
let transport
try {
transport = await TransportWebHID.create()
const ledger = new LaunchpadLedger(transport, { ledgerAppName })
// Check if ledger app is open
await ledger.getCosmosAppVersion()
if (ledgerAppName === 'terra') {
const ledger = new TerraApp(transport)
// Check if ledger app is open
const response = await ledger.getAddressAndPubKey([44, 330, 0, 0, 0], 'terra')
if (!response || !response.bech32_address) {
throw new Error(response.error_message)
}
} else {
const ledger = new LaunchpadLedger(transport, { ledgerAppName })
// Check if ledger app is open
await ledger.getCosmosAppVersion()
}
setInstruction(signInstructions[1])
clearTimeout(retryTimeout)
onConnect(transport)
Expand Down
74 changes: 69 additions & 5 deletions components/DsmAirdrop/CheckAirdrop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ const CheckAirdrop: React.FC<CheckAirdropProps> = ({
<Box>
{dataStakingInfo.map((item, key) => {
const chain = item.chain_name
const dsm = item.dsm_allotted
const { claimed } = item
return (
<Box
display="flex"
Expand All @@ -138,14 +140,41 @@ const CheckAirdrop: React.FC<CheckAirdropProps> = ({
pt={theme.spacing(0.2)}
key={key}
>
<Box pr={theme.spacing(0.2)}>
<Box pr={theme.spacing(0.2)} display="flex" alignItems="center">
<TickIcon />
</Box>
<Typography style={{ color: theme.palette.primary.main, padding: 0 }}>
<Typography
style={{
color: theme.palette.primary.main,
padding: 0,
display: 'flex',
flexDirection: 'row',
}}
>
{t('chain staker', {
chain,
suffix: item.forbole_delegator ? '& Forbole Delegator' : '',
})}
{/* {dsm DSM} */}
{claimed ? (
<Typography
style={{
color: theme.palette.text.secondary,
paddingLeft: theme.spacing(1),
}}
>
{formatCrypto(dsm, 'DSM', lang)} {t('claimed')}
</Typography>
) : (
<Typography
style={{
color: theme.palette.text.primary,
paddingLeft: theme.spacing(1),
}}
>
{formatCrypto(dsm, 'DSM', lang)}
</Typography>
)}
</Typography>
</Box>
)
Expand All @@ -156,6 +185,8 @@ const CheckAirdrop: React.FC<CheckAirdropProps> = ({
<Box pb={theme.spacing(0.2)}>
{lpInfos.map((item, key) => {
const chain = item.chain_name
const dsm = item.dsm_allotted
const { claimed } = item
return (
<Box
display="flex"
Expand All @@ -164,11 +195,37 @@ const CheckAirdrop: React.FC<CheckAirdropProps> = ({
pt={theme.spacing(0.2)}
key={key}
>
<Box pr={theme.spacing(0.2)}>
<Box pr={theme.spacing(0.2)} display="flex" alignItems="center">
<TickIcon />
</Box>
<Typography style={{ color: theme.palette.primary.main, padding: 0 }}>
<Typography
style={{
color: theme.palette.primary.main,
padding: 0,
display: 'flex',
flexDirection: 'row',
}}
>
{chain} {t('lp staker')}
{claimed ? (
<Typography
style={{
color: theme.palette.text.secondary,
paddingLeft: theme.spacing(1),
}}
>
{formatCrypto(dsm, 'DSM', lang)} {t('claimed')}
</Typography>
) : (
<Typography
style={{
color: theme.palette.text.primary,
paddingLeft: theme.spacing(1),
}}
>
{formatCrypto(dsm, 'DSM', lang)}
</Typography>
)}{' '}
</Typography>
</Box>
)
Expand All @@ -178,7 +235,14 @@ const CheckAirdrop: React.FC<CheckAirdropProps> = ({
{(dataStakingInfo !== null && dataStakingInfo !== undefined) ||
(lpInfos !== null && lpInfos !== undefined) ? (
<form noValidate>
<Box mt={4} padding={0} width="20%">
<Typography
style={{
color: theme.palette.text.secondary,
}}
>
{t('check airdrop slogan')}
</Typography>
<Box mt={4} padding={0} minWidth="20%">
<Button
id="button"
variant="contained"
Expand Down
12 changes: 7 additions & 5 deletions components/DsmAirdrop/ClaimableAmount.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,43 +11,45 @@ interface ClaimableAmountProps {
onConfirm(): void
amount: number
chainConnections: ChainConnection[]
loading: boolean
}

const ClaimableAmount: React.FC<ClaimableAmountProps> = ({
onConfirm,
amount,
chainConnections,
loading,
}) => {
const classes = useStyles()
const { t, lang } = useTranslation('common')
const { currency } = useGeneralContext()
const theme = useTheme()

const [loading, setLoading] = React.useState(false)
const [onClaimLoading, setOnClaimLoading] = React.useState(false)

return (
<form
onSubmit={async (event) => {
event.preventDefault()
setLoading(true)
setOnClaimLoading(true)
await onConfirm()
}}
>
<Box display="flex" justifyContent="center">
<Box className={classes.stageContent}>
<Typography align="center">{t('amount claimable title')}</Typography>
<Typography align="center" variant="h1" className={classes.claimableAmount}>
{formatCrypto(amount, 'DSM', lang)}
{loading ? <CircularProgress /> : formatCrypto(amount, 'DSM', lang)}
</Typography>
<Button
fullWidth
color="primary"
className={classes.button}
variant="contained"
type="submit"
disabled={loading || amount <= 0}
// disabled={amount <= 0}
>
{loading ? <CircularProgress size={theme.spacing(3)} /> : t('claim now')}
{onClaimLoading ? <CircularProgress size={theme.spacing(3)} /> : t('claim now')}
</Button>
<Link href="/">
<Button fullWidth className={classes.secondaryButton} variant="outlined">
Expand Down
21 changes: 18 additions & 3 deletions components/DsmAirdrop/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React, { useCallback, useEffect, useState } from 'react'
import useTranslation from 'next-translate/useTranslation'
import { useSubscription, gql } from '@apollo/client'
import axios from 'axios'
import get from 'lodash/get'
import useStateHistory from '../../misc/useStateHistory'
import { useStyles } from './styles'
import CheckClaimable from './CheckClaimable'
Expand All @@ -16,6 +17,7 @@ import ConnectChains from './ConnectChain'
import ClaimableAmount from './ClaimableAmount'
import AirdropResult from './AirdropResult'
import CheckAirdrop from './CheckAirdrop'
import connectableChains from '../../misc/connectableChains'

interface Content {
title?: string
Expand Down Expand Up @@ -70,6 +72,7 @@ const DsmAirdrop: React.FC = () => {
)

const [totalDsmAllocated, setTotalDsmAllocated] = useState(0)
const [totalDsmAllocatedLoading, setTotalDsmAllocatedLoading] = useState(false)
const [airdropResponse, setAirdropResponse] = useState('')

const [claimSuccess, setClaimSuccess] = useState(false)
Expand All @@ -93,6 +96,7 @@ const DsmAirdrop: React.FC = () => {

useEffect(() => {
if (chainConnections.length > 0) {
setTotalDsmAllocatedLoading(true)
const axiosRequests = chainConnections.map((connection) =>
axios.get(
`${process.env.NEXT_PUBLIC_DSM_AIRDROP_API_URL}/users/${connection.externalAddress}`
Expand All @@ -102,19 +106,29 @@ const DsmAirdrop: React.FC = () => {
.all(axiosRequests)
.then(
axios.spread((...responses) => {
responses.forEach((res) => {
responses.forEach((res, i) => {
const chainClaimableAmount = [
...(res.data.staking_infos ?? []),
...(res.data.lp_infos ?? []),
]
.filter((chain) => !chain.claimed)
.filter(
(chain) =>
!chain.claimed &&
chainConnections[i].externalAddress.match(
new RegExp(
`^${get(connectableChains, `${chain.chain_name.toLowerCase()}.prefix`)}`
)
)
)
.reduce((a, b) => a + b.dsm_allotted, 0)
return setTotalDsmAllocated(totalDsmAllocated + chainClaimableAmount)
return setTotalDsmAllocated((total) => total + chainClaimableAmount)
})
setTotalDsmAllocatedLoading(false)
})
)
.catch((error) => {
console.log(error)
// setTotalDsmAllocatedLoading(false)
})
}
}, [chainConnections])
Expand Down Expand Up @@ -151,6 +165,7 @@ const DsmAirdrop: React.FC = () => {
}}
amount={totalDsmAllocated}
chainConnections={chainConnections}
loading={totalDsmAllocatedLoading}
/>
),
}
Expand Down
4 changes: 3 additions & 1 deletion locales/en/common.json
Original file line number Diff line number Diff line change
Expand Up @@ -478,5 +478,7 @@
"airdrop connect account subtitle": "Now it’s time to connect your Desmos Profile to your first wallet account and claim your airdrop for such an account",
"chain staker": "{{chain}} Staker {{suffix}}",
"claim later": "Claim Later",
"claim disabled": "Claim Disabled"
"claim disabled": "Claim Disabled",
"claimed": "claimed",
"check airdrop slogan": "*The more accounts you connected, the more DSM you could claim"
}
6 changes: 3 additions & 3 deletions misc/connectableChains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ const connectableChains = {
coinType: 118,
ledgerAppNames: ['cosmos'],
},
cro: {
'crypto.org chain': {
name: 'Crypto.org',
image: '/static/images/cryptocurrencies/cro.png',
prefix: 'cro',
coinType: 118,
ledgerAppNames: ['cosmos'],
coinType: 394,
ledgerAppNames: ['crypto.org chain', 'cosmos'],
},
terra: {
name: 'Terra',
Expand Down
48 changes: 34 additions & 14 deletions misc/tx/estimateGasFee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import get from 'lodash/get'
import { StargateClient } from '@cosmjs/stargate'
import cryptocurrencies from '../cryptocurrencies'

export const transformMsg = (obj: any): any =>
const transformMsg = (obj: any): any =>
transform(obj, (acc, value, key, target) => {
const camelKey = isArray(target) ? key : snakeCase(String(key))
const childKeys = Object.keys(value)
Expand All @@ -20,9 +20,37 @@ export const transformMsg = (obj: any): any =>
}
})

const transformFee = async (
signer: string,
crypto: Cryptocurrency,
gas: number,
granter?: string
) => {
const fee: any = {
amount: [
{ amount: String(Math.round(gas * crypto.gasFee.amount)), denom: crypto.gasFee.denom },
],
gas: String(gas),
}
if (granter) {
try {
const { balances } = await fetch(
`${crypto.lcdApiUrl}/cosmos/bank/v1beta1/balances/${signer}`
).then((r) => r.json())
if (!balances.length) {
fee.granter = granter
}
} catch (err) {
console.log(err)
}
}
return fee
}

const estimateGasFee = async (
tx: Transaction,
account: Account
account: Account,
granter?: string
): Promise<{
amount: Array<{ amount: string; denom: string }>
gas: string
Expand Down Expand Up @@ -75,20 +103,12 @@ const estimateGasFee = async (
const gas =
Math.round(Number(get(result, 'gas_info.gas_used', '0')) * crypto.gasAdjustment) ||
tx.msgs.map((msg) => crypto.defaultGas[msg.typeUrl]).reduce((a, b) => a + b, 0)
return {
amount: [
{ amount: String(Math.round(gas * crypto.gasFee.amount)), denom: crypto.gasFee.denom },
],
gas: String(gas),
}
const fee = await transformFee(account.address, crypto, gas, granter)
return fee
} catch (err) {
const gas = tx.msgs.map((msg) => crypto.defaultGas[msg.typeUrl]).reduce((a, b) => a + b, 0)
return {
amount: [
{ amount: String(Math.round(gas * crypto.gasFee.amount)), denom: crypto.gasFee.denom },
],
gas: String(gas),
}
const fee = await transformFee(account.address, crypto, gas, granter)
return fee
}
}

Expand Down
Loading

0 comments on commit cc2defe

Please sign in to comment.