Skip to content
This repository has been archived by the owner on Oct 31, 2024. It is now read-only.

Commit

Permalink
feat: use new subnet endpoint fields (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastiendan authored Nov 7, 2023
1 parent 9b1abf5 commit ed98efc
Show file tree
Hide file tree
Showing 12 changed files with 48 additions and 61 deletions.
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"@apollo/client": "^3.7.15",
"@emotion/react": "11.10.6",
"@emotion/styled": "11.10.6",
"@topos-protocol/topos-smart-contracts": "^1.2.2",
"@topos-protocol/topos-smart-contracts": "^2.0.0",
"3d-force-graph": "^1.71.4",
"antd": "^5.10.1",
"axios": "^1.4.0",
Expand Down
3 changes: 1 addition & 2 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import AppInternals from './AppInternals'
import { TourRefsContext } from './contexts/tourRefs'
import useSubnetGetLatestBlockNumber from './hooks/useSubnetGetLatestBlockNumber'
import { CrossSubnetMessagesGraphContext } from './contexts/crossSubnetMessagesGraph'
import { sanitizeURLProtocol } from './utils'

const Errors = styled.div`
margin: 1rem auto;
Expand Down Expand Up @@ -68,7 +67,7 @@ const App = () => {
const apolloClient = useMemo(
() =>
new ApolloClient({
uri: sanitizeURLProtocol('http', selectedTCEEndpoint || ''),
uri: selectedTCEEndpoint,
cache: new InMemoryCache(),
}),
[selectedTCEEndpoint]
Expand Down
3 changes: 1 addition & 2 deletions src/components/NetworkSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import { Divider, Form, Input, Select, Space, Button } from 'antd'
import React, { useState, useCallback, useEffect, ReactNode } from 'react'
import { removeURLProtocol } from '../utils'

interface Props {
allowCustomItems: boolean
Expand Down Expand Up @@ -44,7 +43,7 @@ const NetworkSelector = ({
const addItem = useCallback(
(e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => {
e.preventDefault()
setCustomItems((items) => [...items, removeURLProtocol(newCustomItem)])
setCustomItems((items) => [...items, newCustomItem])
setNewCustomItem('')
},
[newCustomItem]
Expand Down
7 changes: 4 additions & 3 deletions src/components/NetworksMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,10 @@ const NetworksMenu = () => {
<Space direction="vertical" size={0}>
<Text>Select a Topos Subnet endpoint</Text>
{Boolean(selectedToposSubnet) && (
<Text
strong
>{`(currently: ${selectedToposSubnet?.endpoint})`}</Text>
<Text strong>{`(currently: ${
selectedToposSubnet?.endpointWs ||
selectedToposSubnet?.endpointHttp
})`}</Text>
)}
</Space>
}
Expand Down
2 changes: 1 addition & 1 deletion src/components/SubnetInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const SubnetInfo = () => {
{selectedSubnet?.currencySymbol}
</Descriptions.Item>
<Descriptions.Item label="RPC Endpoint">
{selectedSubnet?.endpoint}
{selectedSubnet?.endpointWs} | {selectedSubnet?.endpointHttp}
</Descriptions.Item>
</Descriptions>
<Row gutter={16}>
Expand Down
4 changes: 3 additions & 1 deletion src/components/ToposSubnetSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ const ToposSubnetSelector = () => {
label: i,
value: i,
}))}
initialValue={selectedToposSubnet?.endpoint}
initialValue={
selectedToposSubnet?.endpointWs || selectedToposSubnet?.endpointHttp
}
fixedItems={liveNetworkItems.map((i) => ({
label: i,
value: i,
Expand Down
25 changes: 14 additions & 11 deletions src/hooks/useEthers.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
import { ethers } from 'ethers'
import React from 'react'
import { providers } from 'ethers'
import { useContext, useMemo } from 'react'
import SturdyWebSocket from 'sturdy-websocket'

import { Subnet } from '../types'
import { SelectedNetworksContext } from '../contexts/selectedNetworks'
import { sanitizeURLProtocol } from '../utils'

interface Args {
subnet?: Subnet
viaMetaMask?: boolean
}

export default function useEthers({ subnet }: Args = {}) {
const { selectedToposSubnet } = React.useContext(SelectedNetworksContext)
const provider = React.useMemo(() => {
const endpoint = subnet?.endpoint || selectedToposSubnet?.endpoint
const { selectedToposSubnet } = useContext(SelectedNetworksContext)
const provider = useMemo(() => {
const _subnet = subnet || selectedToposSubnet
const _endpoint = _subnet?.endpointWs || _subnet?.endpointHttp

return endpoint
? new ethers.providers.WebSocketProvider(
new SturdyWebSocket(sanitizeURLProtocol('ws', `${endpoint}/ws`))
)
: undefined
if (_endpoint) {
const _url = new URL(_endpoint)
return _url.protocol.startsWith('ws')
? new providers.WebSocketProvider(new SturdyWebSocket(_endpoint))
: new providers.JsonRpcProvider(_endpoint)
}

return
}, [subnet])

return {
Expand Down
13 changes: 7 additions & 6 deletions src/hooks/useSubnetGetLatestBlockNumber.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { providers } from 'ethers'
import { useCallback, useContext } from 'react'
import { ErrorsContext } from '../contexts/errors'

import { ErrorsContext } from '../contexts/errors'
import { Subnet } from '../types'
import { providers } from 'ethers'
import { sanitizeURLProtocol } from '../utils'

export default function useSubnetGetLatestBlockNumber() {
const { setErrors } = useContext(ErrorsContext)

const getSubnetLatestBlockNumber = useCallback((subnet?: Subnet) => {
if (subnet) {
try {
const provider = new providers.JsonRpcProvider(
sanitizeURLProtocol('http', subnet.endpoint)
)
const endpoint = subnet.endpointHttp || subnet.endpointWs
const url = new URL(endpoint)
const provider = url.protocol.startsWith('ws')
? new providers.WebSocketProvider(subnet.endpointWs)
: new providers.JsonRpcProvider(subnet.endpointHttp)
return provider.getBlockNumber()
} catch (error) {
setErrors((e) => [
Expand Down
12 changes: 7 additions & 5 deletions src/hooks/useToposSubnetGetFromEndpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { useCallback, useContext } from 'react'
import { ErrorsContext } from '../contexts/errors'
import { toposCoreContract } from '../contracts'
import { SubnetWithId } from '../types'
import { sanitizeURLProtocol } from '../utils'

export default function useToposSubnetGetFromEndpoint() {
const { setErrors } = useContext(ErrorsContext)
Expand All @@ -14,9 +13,11 @@ export default function useToposSubnetGetFromEndpoint() {
new Promise<SubnetWithId>(async (resolve, reject) => {
if (endpoint) {
try {
const provider = new providers.JsonRpcProvider(
sanitizeURLProtocol('http', endpoint)
)
const url = new URL(endpoint)
const isURLWs = url.protocol.startsWith('ws')
const provider = isURLWs
? new providers.WebSocketProvider(endpoint)
: new providers.JsonRpcProvider(endpoint)

const network = await provider.getNetwork()
const chainId = network.chainId
Expand All @@ -27,7 +28,8 @@ export default function useToposSubnetGetFromEndpoint() {
resolve({
chainId: BigNumber.from(chainId.toString()),
currencySymbol: 'TOPOS',
endpoint,
endpointHttp: isURLWs ? '' : endpoint,
endpointWs: isURLWs ? endpoint : '',
id: subnetId,
logoURL: '/logo.svg',
name: 'Topos Subnet',
Expand Down
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { BigNumber } from 'ethers'
import { Certificate as CertificateFromQuery } from './__generated__/graphql'

export interface Subnet {
endpoint: string
endpointHttp: string
endpointWs: string
logoURL: string
name: string
currencySymbol: string
Expand Down
21 changes: 0 additions & 21 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,3 @@ export function shortenAddress(
address.length - prefixSuffixLength
)}`
}

export function sanitizeURLProtocol(protocol: 'ws' | 'http', endpoint: string) {
return endpoint.indexOf('localhost') === -1 && !isIPAddressWithPort(endpoint)
? `${protocol}s://${endpoint}`
: `${protocol}://${endpoint}`
}

export function removeURLProtocol(endpoint: string) {
return endpoint.startsWith('http://') ||
endpoint.startsWith('https://') ||
endpoint.startsWith('ws://') ||
endpoint.startsWith('wss://')
? new URL(endpoint).host
: endpoint
}

function isIPAddressWithPort(input: string): boolean {
// Regular expression to match an IP address with an optional port
const ipWithPortRegex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(:\d+)?$/
return ipWithPortRegex.test(input)
}

0 comments on commit ed98efc

Please sign in to comment.