Skip to content

Commit

Permalink
Merge pull request #123 from dappforce/deploy/domain-prices
Browse files Browse the repository at this point in the history
Calculate domain price by rpc call
  • Loading branch information
olehmell authored Aug 15, 2023
2 parents 4ef0494 + 46bbbb3 commit 802cf19
Show file tree
Hide file tree
Showing 9 changed files with 121 additions and 9 deletions.
34 changes: 26 additions & 8 deletions src/components/domains/EligibleDomainsSection.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { isFunction } from '@polkadot/util'
import { isEmptyArray, newLogger, parseDomain } from '@subsocial/utils'
import { newLogger, parseDomain } from '@subsocial/utils'
import { Button, Card, Result, Row, Tag } from 'antd'
import BN from 'bn.js'
import clsx from 'clsx'
import React, {FC, useState} from 'react'
import React, { FC, useEffect, useState } from 'react'
import { showErrorMessage } from 'src/components/utils/Message'
import config from 'src/config'
import { getOrInitSubsocialRpc } from 'src/rpc/initSubsocialRpc'
import {
useBuildDomainsWithTldByDomain,
useCreateReloadMyDomains,
useFetchDomains,
useIsReservedWord,
Expand Down Expand Up @@ -35,6 +35,25 @@ type DomainProps = {
domain: DomainEntity
}

const useGetDomainPrice = (domain: string) => {
const [price, setPrice] = useState()

useEffect(() => {
const getPrice = async () => {
const subsocialRpc = getOrInitSubsocialRpc()

const { domain: domainPart } = parseDomain(domain)
const price = await subsocialRpc.calculatePrice(domainPart)

setPrice(price)
}

getPrice().catch(err => log.error('Failed to get domain price', err))
}, [domain])

return price
}

const BLOCK_TIME = 12
const SECS_IN_DAY = 60 * 60 * 24
const BLOCKS_IN_YEAR = new BN((SECS_IN_DAY * 365) / BLOCK_TIME)
Expand All @@ -43,13 +62,12 @@ const BuyDomainSection = ({ domain: { id: domain } }: DomainProps) => {
const reloadMyDomains = useCreateReloadMyDomains()
const { openManageModal } = useManageDomainContext()
const { api, isApiReady } = useSubstrate()
const price = useGetDomainPrice(domain)

if (!isApiReady) return null

const price = api?.consts.domains.baseDomainDeposit.toString()

const getTxParams = () => {
return [domain, null, BLOCKS_IN_YEAR]
return [null, domain, null, BLOCKS_IN_YEAR]
}

const onSuccess: TxCallback = async () => {
Expand Down Expand Up @@ -289,10 +307,10 @@ const SuggestedDomains = ({ domain: { id } }: DomainProps) => {
// }

export const EligibleDomainsSection = ({ domain }: FoundDomainCardProps) => {
const domains = useBuildDomainsWithTldByDomain(domain)
// const domains = useBuildDomainsWithTldByDomain(domain)
const { isReserved, loading: checkingWord } = useIsReservedWord(domain.id)

if (isEmptyArray(domains)) return null
// if (isEmptyArray(domains)) return null

if (checkingWord) return <Loading label='Check domain...' />

Expand Down
2 changes: 1 addition & 1 deletion src/components/domains/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const DomainMarketSection = ({ promoCode }: DomainServerProps) => {
const myDomainsCount = domains.length

const maxPromoDomainsPerAccount =
api?.consts.domains.maxPromoDomainsPerAccount.toHuman() as unknown as number
api?.consts.domains.maxDomainsPerAccount.toHuman() as unknown as number

const canRegisterAccount = myDomainsCount < maxPromoDomainsPerAccount

Expand Down
1 change: 1 addition & 0 deletions src/config/app/staging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ const staging: AppConfig = {
lastReservedSpaceId: '1000',
claimedSpaceIds: [],
recommendedSpaceIds: ['1001', '1002', '1003'],
suggestedTlds: ['sub', 'polka'],
}

export default staging
1 change: 1 addition & 0 deletions src/config/connections/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { SubsocialConfig } from '../types'

const localConfig: SubsocialConfig = {
substrateUrl: 'ws://localhost:8844',
substrateRpcUrl: 'http://localhost:8844',
kusamaUrl: 'wss://staging.subsocial.network/kusama',

offchainUrl: 'http://localhost:3001',
Expand Down
1 change: 1 addition & 0 deletions src/config/connections/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const mainConfig: SubsocialConfig = {
sudoOne: '3osmnRNnrcScHsgkTJH1xyBF5kGjpbWHsGrqM31BJpy4vwn8',

substrateUrl: 'wss://para.subsocial.network',
substrateRpcUrl: 'https://para.subsocial.network/http',
kusamaUrl: 'wss://kusama-rpc.polkadot.io',

offchainUrl: 'https://api.subsocial.network',
Expand Down
1 change: 1 addition & 0 deletions src/config/connections/staging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const stagingConfig: SubsocialConfig = {
sudoOne: '3si9SFRhEPKvpk2xW9dUkcud1AanQxJwok2QFqppqE5ZeShp',

substrateUrl: 'wss://rco-para.subsocial.network',
substrateRpcUrl: 'https://rco-para.subsocial.network/http',
offchainUrl: 'https://staging-api.subsocial.network',
offchainSignerUrl: 'https://staging-signer.subsocial.network',
graphqlUrl: 'https://squid.subsquid.io/soonsocial/graphql',
Expand Down
3 changes: 3 additions & 0 deletions src/config/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ export type ConnectionsSettings = {
/** A URL of a Substrate node. Example: `'ws://localhost:9944'`. */
substrateUrl: string

/** Rpc URL of a Substrate node. Example: `'http://localhost:9944'`. */
substrateRpcUrl: string

/** A URL of a Kusama node. Example: `'kusama-rpc.polkadot.io'`. */
kusamaUrl?: string

Expand Down
73 changes: 73 additions & 0 deletions src/rpc/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { stringToU8a } from '@polkadot/util'
import { newLogger } from '@subsocial/utils'
import axios from 'axios'
import { PalletName } from 'src/types'

type SubstrateApiProps = {
rpcUrl: string
}

type RpcParams = any[]

type StorageItem = {
moduleName: PalletName
method: string
}

type RpcResult = {
result: any
}

const createRpcJson = ({ moduleName, method }: StorageItem, params: RpcParams) => ({
jsonrpc: '2.0',
id: 1,
method: `${moduleName}_${method}`,
params,
})

const log = newLogger('SubsocialSubstrateRpc')

export class SubsocialSubstrateRpc {
private rpcUrl: string

constructor({ rpcUrl }: SubstrateApiProps) {
this.rpcUrl = rpcUrl
log.info('Initialized')
}

// ---------------------------------------------------------------------
// Private utils

private async rpcQuery<Params, Result = any>(
method: StorageItem,
value?: Params,
): Promise<Result | undefined> {
try {
const params = Array.isArray(value) ? value : [value]
const { data, status, statusText } = await axios.post<RpcResult>(
this.rpcUrl,
createRpcJson(method, [...params]),
{ headers: { 'Content-Type': 'application/json' } },
)

if (status !== 200) {
throw statusText
}

return data.result
} catch (err) {
log.error('Failed rpc method:', err)
return undefined
}
}

private async queryDomains(method: string, value?: any): Promise<any> {
return this.rpcQuery({ moduleName: 'domains', method }, value)
}

async calculatePrice(domain: string): Promise<any> {
const domainU8a = stringToU8a(domain)

return this.queryDomains('calculatePrice', [Array.from(domainU8a)])
}
}
14 changes: 14 additions & 0 deletions src/rpc/initSubsocialRpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import config from 'src/config'
import { SubsocialSubstrateRpc } from '.'

const { substrateRpcUrl } = config

let subsocialRpc: SubsocialSubstrateRpc | undefined = undefined

export const getOrInitSubsocialRpc = () => {
if (!subsocialRpc) {
subsocialRpc = new SubsocialSubstrateRpc({ rpcUrl: substrateRpcUrl })
}

return subsocialRpc
}

0 comments on commit 802cf19

Please sign in to comment.