feat: add stamp dilute and topup (#619)
* feat: add stamp dilute and topup * fix: remove any * chore: bump bee-js * chore: remove obsolete workaround
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
import { ReactElement, ReactNode } from 'react'
|
||||
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles'
|
||||
import { Typography, Grid, IconButton, Tooltip } from '@material-ui/core'
|
||||
import Info from 'remixicon-react/InformationLineIcon'
|
||||
import { Grid, IconButton, Tooltip, Typography } from '@material-ui/core'
|
||||
import ListItem from '@material-ui/core/ListItem'
|
||||
import { Theme, createStyles, makeStyles } from '@material-ui/core/styles'
|
||||
import { ReactElement, ReactNode } from 'react'
|
||||
import Info from 'remixicon-react/InformationLineIcon'
|
||||
|
||||
const useStyles = makeStyles((theme: Theme) =>
|
||||
createStyles({
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { BeeDebug } from '@ethersphere/bee-js'
|
||||
import Button from '@material-ui/core/Button'
|
||||
import Dialog from '@material-ui/core/Dialog'
|
||||
import DialogActions from '@material-ui/core/DialogActions'
|
||||
import DialogContent from '@material-ui/core/DialogContent'
|
||||
import DialogTitle from '@material-ui/core/DialogTitle'
|
||||
import Input from '@material-ui/core/Input'
|
||||
import { useSnackbar } from 'notistack'
|
||||
import { ReactElement, ReactNode, useState } from 'react'
|
||||
import { SwarmSelect } from './SwarmSelect'
|
||||
|
||||
interface Props {
|
||||
label: string
|
||||
icon: ReactNode
|
||||
beeDebug: BeeDebug
|
||||
stamp: string
|
||||
}
|
||||
|
||||
export default function StampExtensionModal({ label, icon, beeDebug, stamp }: Props): ReactElement {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [amount, setAmount] = useState('')
|
||||
const [type, setType] = useState<'Topup' | 'Dilute'>('Topup')
|
||||
const { enqueueSnackbar } = useSnackbar()
|
||||
|
||||
const handleClickOpen = (e: React.MouseEvent<HTMLButtonElement>) => {
|
||||
setOpen(true)
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const handleAction = async () => {
|
||||
if (type === 'Topup') {
|
||||
try {
|
||||
await beeDebug.topUpBatch(stamp, amount)
|
||||
enqueueSnackbar(`Successfully topped up stamp, your changes will appear soon`, { variant: 'success' })
|
||||
} catch (error) {
|
||||
enqueueSnackbar(`Failed to topup stamp: ${error || 'Unknown reason'}`, { variant: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
if (type === 'Dilute') {
|
||||
try {
|
||||
await beeDebug.diluteBatch(stamp, parseInt(amount, 10))
|
||||
enqueueSnackbar(`Successfully diluted stamp, your changes will appear soon`, { variant: 'success' })
|
||||
} catch (error) {
|
||||
enqueueSnackbar(`Failed to dilute stamp: ${error || 'Unknown reason'}`, { variant: 'error' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
|
||||
setAmount(event.target.value)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button variant="contained" onClick={handleClickOpen} startIcon={icon}>
|
||||
{label}
|
||||
</Button>
|
||||
<Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title">
|
||||
<DialogTitle id="form-dialog-title">{label}</DialogTitle>
|
||||
<DialogContent>
|
||||
<SwarmSelect
|
||||
label="Action"
|
||||
defaultValue="Topup"
|
||||
onChange={event => setType(event.target.value as 'Topup' | 'Dilute')}
|
||||
options={[
|
||||
{ value: 'Topup', label: 'Topup' },
|
||||
{ value: 'Dilute', label: 'Dilute' },
|
||||
]}
|
||||
/>
|
||||
<Input
|
||||
autoFocus
|
||||
margin="dense"
|
||||
id="name"
|
||||
type="text"
|
||||
placeholder={type === 'Topup' ? 'Amount to add' : 'New depth to dilute'}
|
||||
fullWidth
|
||||
value={amount}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleClose} color="primary">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleAction} color="primary">
|
||||
{type}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -30,6 +30,7 @@ interface Props {
|
||||
formik?: boolean
|
||||
defaultValue?: string
|
||||
placeholder?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const useStyles = makeStyles((theme: Theme) =>
|
||||
@@ -60,6 +61,7 @@ export function SwarmSelect({
|
||||
onChange,
|
||||
label,
|
||||
placeholder,
|
||||
disabled = false,
|
||||
}: Props): ReactElement {
|
||||
const classes = useStyles()
|
||||
|
||||
@@ -69,6 +71,7 @@ export function SwarmSelect({
|
||||
{label && <FormHelperText>{label}</FormHelperText>}
|
||||
<Field
|
||||
required
|
||||
disabled={disabled}
|
||||
component={Select}
|
||||
name={name}
|
||||
fullWidth
|
||||
@@ -94,6 +97,7 @@ export function SwarmSelect({
|
||||
{label && <FormHelperText>{label}</FormHelperText>}
|
||||
<MuiSelect
|
||||
required
|
||||
disabled={disabled}
|
||||
name={name}
|
||||
fullWidth
|
||||
variant="outlined"
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { CircularProgress, Container, createStyles, makeStyles } from '@material-ui/core'
|
||||
import { CircularProgress, createStyles, makeStyles } from '@material-ui/core'
|
||||
import { ReactElement, useContext, useEffect } from 'react'
|
||||
import PlusSquare from 'remixicon-react/AddBoxLineIcon'
|
||||
import { useNavigate } from 'react-router'
|
||||
import PlusSquare from 'remixicon-react/AddBoxLineIcon'
|
||||
import { Loading } from '../../../components/Loading'
|
||||
import { SwarmButton } from '../../../components/SwarmButton'
|
||||
import TroubleshootConnectionCard from '../../../components/TroubleshootConnectionCard'
|
||||
import { CheckState, Context as BeeContext } from '../../../providers/Bee'
|
||||
import { Context as BeeContext, CheckState } from '../../../providers/Bee'
|
||||
import { Context as StampsContext } from '../../../providers/Stamps'
|
||||
import { ROUTES } from '../../../routes'
|
||||
import StampsTable from '../../stamps/StampsTable'
|
||||
@@ -53,11 +54,7 @@ export function AccountStamps(): ReactElement {
|
||||
<Header />
|
||||
<AccountNavigation active="STAMPS" />
|
||||
<div className={classes.root}>
|
||||
{error && (
|
||||
<Container style={{ textAlign: 'center', padding: '50px' }}>
|
||||
Error loading postage stamps details: {error.message}
|
||||
</Container>
|
||||
)}
|
||||
{error && <Loading />}
|
||||
{!error && (
|
||||
<>
|
||||
<div className={classes.actions}>
|
||||
|
||||
@@ -14,13 +14,15 @@ interface Props {
|
||||
}
|
||||
|
||||
export default function PeerBalances({ accounting, isLoadingUncashed, totalUncashed }: Props): ReactElement | null {
|
||||
const uncashedPeers = accounting?.filter(({ uncashedAmount }) => uncashedAmount.toBigNumber.isGreaterThan('0')) || []
|
||||
|
||||
return (
|
||||
<ExpandableList
|
||||
label={`Peers (${accounting?.length || 0})`}
|
||||
label={`Peers (${uncashedPeers.length})`}
|
||||
info={`${totalUncashed.toFixedDecimal()} xBZZ (uncashed)`}
|
||||
>
|
||||
<ExpandableListItem label="Uncashed Amount Total" value={`${totalUncashed.toFixedDecimal()} xBZZ`} />
|
||||
{accounting?.map(({ peer, balance, received, sent, uncashedAmount, total }) => (
|
||||
{uncashedPeers.map(({ peer, balance, received, sent, uncashedAmount, total }) => (
|
||||
<ExpandableList
|
||||
key={peer}
|
||||
label={`Peer ${peer.slice(0, 8)}[…]`}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import * as swarmCid from '@ethersphere/swarm-cid'
|
||||
import { Box } from '@material-ui/core'
|
||||
import { ReactElement, useContext, useEffect, useState } from 'react'
|
||||
import X from 'remixicon-react/CloseLineIcon'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import X from 'remixicon-react/CloseLineIcon'
|
||||
import { DocumentationText } from '../../components/DocumentationText'
|
||||
import ExpandableListItemActions from '../../components/ExpandableListItemActions'
|
||||
import ExpandableListItemKey from '../../components/ExpandableListItemKey'
|
||||
import ExpandableListItemLink from '../../components/ExpandableListItemLink'
|
||||
import { HistoryHeader } from '../../components/HistoryHeader'
|
||||
import { SwarmButton } from '../../components/SwarmButton'
|
||||
import { Context as BeeContext } from '../../providers/Bee'
|
||||
@@ -55,14 +53,8 @@ export function FeedSubpage(): ReactElement {
|
||||
<UploadArea showHelp={false} uploadOrigin={{ origin: 'FEED', uuid }} />
|
||||
{available && identity.feedHash ? (
|
||||
<>
|
||||
<Box mb={0.25}>
|
||||
<ExpandableListItemKey label="Feed hash" value={identity.feedHash} />
|
||||
</Box>
|
||||
<Box mb={4}>
|
||||
<ExpandableListItemLink
|
||||
label="BZZ Link"
|
||||
value={`https://${swarmCid.encodeFeedReference(identity.feedHash)}.bzz.link`}
|
||||
/>
|
||||
<ExpandableListItemKey label="Feed hash" value={identity.feedHash} />
|
||||
</Box>
|
||||
</>
|
||||
) : (
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import * as swarmCid from '@ethersphere/swarm-cid'
|
||||
import { Utils } from '@ethersphere/bee-js'
|
||||
import { Box } from '@material-ui/core'
|
||||
import { ReactElement } from 'react'
|
||||
import { Utils } from '@ethersphere/bee-js'
|
||||
import { DocumentationText } from '../../components/DocumentationText'
|
||||
import ExpandableListItemKey from '../../components/ExpandableListItemKey'
|
||||
import ExpandableListItemLink from '../../components/ExpandableListItemLink'
|
||||
@@ -19,16 +18,6 @@ export function AssetSummary({ isWebsite, reference }: Props): ReactElement {
|
||||
<Box mb={4}>
|
||||
{isHash && <ExpandableListItemKey label="Swarm hash" value={reference} />}
|
||||
{!isHash && <ExpandableListItemLink label="ENS" value={reference} />}
|
||||
<ExpandableListItemLink
|
||||
label="Share on Swarm Gateway"
|
||||
value={`https://gateway.ethswarm.org/access/${reference}`}
|
||||
/>
|
||||
{isWebsite && isHash && (
|
||||
<ExpandableListItemLink
|
||||
label="BZZ Link"
|
||||
value={`https://${swarmCid.encodeManifestReference(reference).toString()}.bzz.link`}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<DocumentationText>
|
||||
The Swarm Gateway is graciously provided by the Swarm Foundation. This service is under development and provided
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { BeeModes, Utils } from '@ethersphere/bee-js'
|
||||
import { ManifestJs } from '@ethersphere/manifest-js'
|
||||
import { useSnackbar } from 'notistack'
|
||||
import { ReactElement, useContext, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import Search from 'remixicon-react/SearchLineIcon'
|
||||
import ExpandableListItemInput from '../../components/ExpandableListItemInput'
|
||||
import { History } from '../../components/History'
|
||||
import { Context as BeeContext } from '../../providers/Bee'
|
||||
import { Context as FileContext, defaultUploadOrigin } from '../../providers/File'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { Context as BeeContext } from '../../providers/Bee'
|
||||
import { ROUTES } from '../../routes'
|
||||
import { recognizeEnsOrSwarmHash, regexpEns } from '../../utils'
|
||||
import { determineHistoryName, HISTORY_KEYS, putHistory } from '../../utils/local-storage'
|
||||
import { ManifestJs } from '../../utils/manifest'
|
||||
import { FileNavigation } from './FileNavigation'
|
||||
|
||||
export function Download(): ReactElement {
|
||||
@@ -34,9 +34,7 @@ export function Download(): ReactElement {
|
||||
) {
|
||||
setReferenceError(undefined)
|
||||
} else {
|
||||
setReferenceError(
|
||||
'Incorrect format of swarm hash. Expected 64 or 128 hexstring characters, bzz.link url or ENS domain.',
|
||||
)
|
||||
setReferenceError('Incorrect format of swarm hash. Expected 64 or 128 hexstring characters or ENS domain.')
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ManifestJs } from '@ethersphere/manifest-js'
|
||||
import { Box, Typography } from '@material-ui/core'
|
||||
import { saveAs } from 'file-saver'
|
||||
import JSZip from 'jszip'
|
||||
@@ -13,6 +12,7 @@ import { Context as BeeContext } from '../../providers/Bee'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { ROUTES } from '../../routes'
|
||||
import { determineHistoryName, HISTORY_KEYS, putHistory } from '../../utils/local-storage'
|
||||
import { ManifestJs } from '../../utils/manifest'
|
||||
import { AssetPreview } from './AssetPreview'
|
||||
import { AssetSummary } from './AssetSummary'
|
||||
import { DownloadActionBar } from './DownloadActionBar'
|
||||
|
||||
@@ -7,11 +7,11 @@ import { HistoryHeader } from '../../components/HistoryHeader'
|
||||
import { ProgressIndicator } from '../../components/ProgressIndicator'
|
||||
import TroubleshootConnectionCard from '../../components/TroubleshootConnectionCard'
|
||||
import { META_FILE_NAME, PREVIEW_FILE_NAME } from '../../constants'
|
||||
import { CheckState, Context as BeeContext } from '../../providers/Bee'
|
||||
import { Context as IdentityContext, Identity } from '../../providers/Feeds'
|
||||
import { Context as BeeContext, CheckState } from '../../providers/Bee'
|
||||
import { Identity, Context as IdentityContext } from '../../providers/Feeds'
|
||||
import { Context as FileContext } from '../../providers/File'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { Context as StampsContext, EnrichedPostageBatch } from '../../providers/Stamps'
|
||||
import { EnrichedPostageBatch, Context as StampsContext } from '../../providers/Stamps'
|
||||
import { ROUTES } from '../../routes'
|
||||
import { waitUntilStampUsable } from '../../utils'
|
||||
import { detectIndexHtml, getAssetNameFromFiles, packageFile } from '../../utils/file'
|
||||
@@ -130,7 +130,7 @@ export function Upload(): ReactElement {
|
||||
}
|
||||
|
||||
beeApi
|
||||
.uploadFiles(stamp.batchID, fls, { indexDocument })
|
||||
.uploadFiles(stamp.batchID, fls, { indexDocument, deferred: true })
|
||||
.then(hash => {
|
||||
putHistory(HISTORY_KEYS.UPLOAD_HISTORY, hash.reference, getAssetNameFromFiles(files))
|
||||
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import { Box, Tooltip, Typography } from '@material-ui/core'
|
||||
import { Wallet } from 'ethers'
|
||||
import { useSnackbar } from 'notistack'
|
||||
import { ReactElement, useContext, useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import Check from 'remixicon-react/CheckLineIcon'
|
||||
import X from 'remixicon-react/CloseLineIcon'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Wallet } from 'ethers'
|
||||
import ExpandableListItem from '../../components/ExpandableListItem'
|
||||
import ExpandableListItemActions from '../../components/ExpandableListItemActions'
|
||||
import ExpandableListItemKey from '../../components/ExpandableListItemKey'
|
||||
import { HistoryHeader } from '../../components/HistoryHeader'
|
||||
import { Loading } from '../../components/Loading'
|
||||
import { SwarmButton } from '../../components/SwarmButton'
|
||||
import { Context as BalanceProvider } from '../../providers/WalletBalance'
|
||||
import { Context as TopUpContext } from '../../providers/TopUp'
|
||||
import { Token } from '../../models/Token'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
import { Context as TopUpContext } from '../../providers/TopUp'
|
||||
import { Context as BalanceProvider } from '../../providers/WalletBalance'
|
||||
import { createGiftWallet } from '../../utils/desktop'
|
||||
import { ResolvedWallet } from '../../utils/wallet'
|
||||
import { Token } from '../../models/Token'
|
||||
|
||||
const GIFT_WALLET_FUND_DAI_AMOUNT = Token.fromDecimal('0.1', 18)
|
||||
const GIFT_WALLET_FUND_BZZ_AMOUNT = Token.fromDecimal('0.5', 16)
|
||||
@@ -31,6 +31,9 @@ export default function Index(): ReactElement {
|
||||
|
||||
useEffect(() => {
|
||||
async function mapGiftWallets() {
|
||||
if (!rpcProvider) {
|
||||
return
|
||||
}
|
||||
const results = []
|
||||
for (const giftWallet of giftWallets) {
|
||||
results.push(await ResolvedWallet.make(giftWallet, rpcProvider))
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { PostageBatchOptions } from '@ethersphere/bee-js'
|
||||
import { Box, Grid, Typography } from '@material-ui/core'
|
||||
import BigNumber from 'bignumber.js'
|
||||
import { Form, Formik, FormikHelpers } from 'formik'
|
||||
import { useSnackbar } from 'notistack'
|
||||
import { ReactElement, useContext } from 'react'
|
||||
import { ReactElement, useContext, useEffect, useState } from 'react'
|
||||
import Check from 'remixicon-react/CheckLineIcon'
|
||||
import { SwarmButton } from '../../components/SwarmButton'
|
||||
import { SwarmSelect } from '../../components/SwarmSelect'
|
||||
import { SwarmTextInput } from '../../components/SwarmTextInput'
|
||||
import { Context as BeeContext } from '../../providers/Bee'
|
||||
import { Context as SettingsContext } from '../../providers/Settings'
|
||||
@@ -19,18 +19,6 @@ import {
|
||||
} from '../../utils'
|
||||
import { getHumanReadableFileSize } from '../../utils/file'
|
||||
|
||||
interface FormValues {
|
||||
depth?: string
|
||||
amount?: string
|
||||
label?: string
|
||||
}
|
||||
type FormErrors = Partial<FormValues>
|
||||
const initialFormValues: FormValues = {
|
||||
depth: '',
|
||||
amount: '',
|
||||
label: '',
|
||||
}
|
||||
|
||||
interface Props {
|
||||
onFinished: () => void
|
||||
}
|
||||
@@ -40,6 +28,13 @@ export function PostageStampCreation({ onFinished }: Props): ReactElement {
|
||||
const { refresh } = useContext(StampsContext)
|
||||
const { beeDebugApi } = useContext(SettingsContext)
|
||||
|
||||
const [depthInput, setDepthInput] = useState<string>('')
|
||||
const [amountInput, setAmountInput] = useState<string>('')
|
||||
const [labelInput, setLabelInput] = useState('')
|
||||
const [immutable, setImmutable] = useState(false)
|
||||
const [errors, setErrors] = useState<Record<string, string>>({})
|
||||
const [submitting, setSubmitting] = useState(false)
|
||||
|
||||
const { enqueueSnackbar } = useSnackbar()
|
||||
|
||||
function getFileSize(depth: number): string {
|
||||
@@ -76,6 +71,73 @@ export function PostageStampCreation({ onFinished }: Props): ReactElement {
|
||||
return `${price.toSignificantDigits()} xBZZ`
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
try {
|
||||
// This is really just a typeguard, the validation pretty much guarantees these will have the right values
|
||||
if (!depthInput || !amountInput) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!beeDebugApi) {
|
||||
return
|
||||
}
|
||||
|
||||
setSubmitting(true)
|
||||
const amount = BigInt(amountInput)
|
||||
const depth = Number.parseInt(depthInput)
|
||||
const options: PostageBatchOptions = {
|
||||
waitForUsable: false,
|
||||
label: labelInput || undefined,
|
||||
immutableFlag: immutable,
|
||||
}
|
||||
|
||||
const batchId = await beeDebugApi.createPostageBatch(amount.toString(), depth, options)
|
||||
await waitUntilStampExists(batchId, beeDebugApi)
|
||||
await refresh()
|
||||
onFinished()
|
||||
} catch (e) {
|
||||
console.error(e) // eslint-disable-line
|
||||
enqueueSnackbar(`Error: ${(e as Error).message}`, { variant: 'error' })
|
||||
}
|
||||
setSubmitting(false)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
function validate() {
|
||||
const errors: Record<string, string> = {}
|
||||
|
||||
if (!depthInput) {
|
||||
errors.depth = 'Required field'
|
||||
} else {
|
||||
const depth = new BigNumber(depthInput)
|
||||
|
||||
if (!depth.isInteger()) {
|
||||
errors.depth = 'Depth must be an integer'
|
||||
} else if (depth.isLessThan(17)) {
|
||||
errors.depth = 'Minimal depth is 17'
|
||||
} else if (depth.isGreaterThan(255)) {
|
||||
errors.depth = 'Depth has to be at most 255'
|
||||
}
|
||||
}
|
||||
|
||||
if (!amountInput) {
|
||||
errors.amount = 'Required field'
|
||||
} else {
|
||||
const amount = new BigNumber(amountInput)
|
||||
|
||||
if (!amount.isInteger()) {
|
||||
errors.amount = 'Amount must be an integer'
|
||||
} else if (amount.isLessThanOrEqualTo(0)) {
|
||||
errors.amount = 'Amount must be greater than 0'
|
||||
}
|
||||
}
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
setErrors(validate())
|
||||
}, [depthInput, amountInput])
|
||||
|
||||
return (
|
||||
<>
|
||||
<Box mb={4}>
|
||||
@@ -92,102 +154,72 @@ export function PostageStampCreation({ onFinished }: Props): ReactElement {
|
||||
.
|
||||
</Typography>
|
||||
</Box>
|
||||
<Formik
|
||||
initialValues={initialFormValues}
|
||||
onSubmit={async (values: FormValues, actions: FormikHelpers<FormValues>) => {
|
||||
try {
|
||||
// This is really just a typeguard, the validation pretty much guarantees these will have the right values
|
||||
if (!values.depth || !values.amount) return
|
||||
|
||||
if (!beeDebugApi) return
|
||||
|
||||
const amount = BigInt(values.amount)
|
||||
const depth = Number.parseInt(values.depth)
|
||||
const options: PostageBatchOptions = { waitForUsable: false, label: values.label || undefined }
|
||||
const batchId = await beeDebugApi.createPostageBatch(amount.toString(), depth, options)
|
||||
await waitUntilStampExists(batchId, beeDebugApi)
|
||||
actions.resetForm()
|
||||
await refresh()
|
||||
onFinished()
|
||||
} catch (e) {
|
||||
console.error(e) // eslint-disable-line
|
||||
enqueueSnackbar(`Error: ${(e as Error).message}`, { variant: 'error' })
|
||||
actions.setSubmitting(false)
|
||||
}
|
||||
}}
|
||||
validate={(values: FormValues) => {
|
||||
const errors: FormErrors = {}
|
||||
|
||||
// Depth
|
||||
if (!values.depth) errors.depth = 'Required field'
|
||||
else {
|
||||
const depth = new BigNumber(values.depth)
|
||||
|
||||
if (!depth.isInteger()) errors.depth = 'Depth must be an integer'
|
||||
else if (depth.isLessThan(17)) errors.depth = 'Minimal depth is 17'
|
||||
else if (depth.isGreaterThan(255)) errors.depth = 'Depth has to be at most 255'
|
||||
}
|
||||
|
||||
// Amount
|
||||
if (!values.amount) errors.amount = 'Required field'
|
||||
else {
|
||||
const amount = new BigNumber(values.amount)
|
||||
|
||||
if (!amount.isInteger()) errors.amount = 'Amount must be an integer'
|
||||
else if (amount.isLessThanOrEqualTo(0)) errors.amount = 'Amount must be greater than 0'
|
||||
}
|
||||
|
||||
return errors
|
||||
}}
|
||||
<Box mb={2}>
|
||||
<SwarmTextInput name="depth" label="Depth" onChange={event => setDepthInput(event.target.value)} />
|
||||
<Box mt={0.25} sx={{ bgcolor: '#f6f6f6' }} p={2}>
|
||||
<Grid container justifyContent="space-between">
|
||||
<Typography>Corresponding file size</Typography>
|
||||
<Typography>{!errors.depth && depthInput ? getFileSize(parseInt(depthInput, 10)) : '-'}</Typography>
|
||||
</Grid>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box mb={2}>
|
||||
<SwarmTextInput name="amount" label="Amount" onChange={event => setAmountInput(event.target.value)} />
|
||||
<Box mt={0.25} sx={{ bgcolor: '#f6f6f6' }} p={2}>
|
||||
<Grid container justifyContent="space-between">
|
||||
<Typography>Corresponding TTL (Time to live)</Typography>
|
||||
<Typography>{!errors.amount && amountInput ? getTtl(Number.parseInt(amountInput, 10)) : '-'}</Typography>
|
||||
</Grid>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box mb={2}>
|
||||
<SwarmTextInput name="label" label="Label" optional onChange={event => setLabelInput(event.target.value)} />
|
||||
</Box>
|
||||
<Box mb={2}>
|
||||
<SwarmSelect
|
||||
label="Immutable"
|
||||
defaultValue="No"
|
||||
onChange={event => setImmutable(event.target.value === 'Yes')}
|
||||
options={[
|
||||
{ value: 'Yes', label: 'Yes' },
|
||||
{ value: 'No', label: 'No' },
|
||||
]}
|
||||
/>
|
||||
<Box mt={0.25} sx={{ bgcolor: '#f6f6f6' }} p={2}>
|
||||
<Grid container justifyContent="space-between">
|
||||
{immutable && (
|
||||
<Typography>
|
||||
Once an immutable stamp is maxed out, it disallows further content uploads, thereby safeguarding your
|
||||
previously uploaded content from unintentional overwriting.
|
||||
</Typography>
|
||||
)}
|
||||
{!immutable && (
|
||||
<Typography>
|
||||
When a mutable stamp reaches full capacity, it still permits new content uploads. However, this comes
|
||||
with the caveat of overwriting previously uploaded content associated with the same stamp.
|
||||
</Typography>
|
||||
)}
|
||||
</Grid>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box mb={4} sx={{ bgcolor: '#fcf2e8' }} p={2}>
|
||||
<Grid container justifyContent="space-between">
|
||||
<Typography>Indicative Price</Typography>
|
||||
<Typography>
|
||||
{!errors.amount && !errors.depth && amountInput && depthInput
|
||||
? getPrice(parseInt(depthInput, 10), BigInt(amountInput))
|
||||
: '-'}
|
||||
</Typography>
|
||||
</Grid>
|
||||
</Box>
|
||||
<SwarmButton
|
||||
disabled={submitting || Object.keys(errors).length > 0}
|
||||
onClick={submit}
|
||||
iconType={Check}
|
||||
loading={submitting}
|
||||
>
|
||||
{({ submitForm, isValid, isSubmitting, values, errors }) => (
|
||||
<Form>
|
||||
<Box mb={2}>
|
||||
<SwarmTextInput name="depth" label="Depth" formik />
|
||||
<Box mt={0.25} sx={{ bgcolor: '#f6f6f6' }} p={2}>
|
||||
<Grid container justifyContent="space-between">
|
||||
<Typography>Corresponding file size</Typography>
|
||||
<Typography>
|
||||
{!errors.depth && values.depth ? getFileSize(parseInt(values.depth, 10)) : '-'}
|
||||
</Typography>
|
||||
</Grid>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box mb={2}>
|
||||
<SwarmTextInput name="amount" label="Amount" formik />
|
||||
<Box mt={0.25} sx={{ bgcolor: '#f6f6f6' }} p={2}>
|
||||
<Grid container justifyContent="space-between">
|
||||
<Typography>Corresponding TTL (Time to live)</Typography>
|
||||
<Typography>
|
||||
{!errors.amount && values.amount ? getTtl(Number.parseInt(values.amount, 10)) : '-'}
|
||||
</Typography>
|
||||
</Grid>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box mb={2}>
|
||||
<SwarmTextInput name="label" label="Label" optional formik />
|
||||
</Box>
|
||||
<Box mb={4} sx={{ bgcolor: '#fcf2e8' }} p={2}>
|
||||
<Grid container justifyContent="space-between">
|
||||
<Typography>Indicative Price</Typography>
|
||||
<Typography>
|
||||
{!errors.amount && !errors.depth && values.amount && values.depth
|
||||
? getPrice(parseInt(values.depth, 10), BigInt(values.amount))
|
||||
: '-'}
|
||||
</Typography>
|
||||
</Grid>
|
||||
</Box>
|
||||
<SwarmButton
|
||||
disabled={isSubmitting || !isValid || !values.amount || !values.depth}
|
||||
onClick={submitForm}
|
||||
iconType={Check}
|
||||
loading={isSubmitting}
|
||||
>
|
||||
Buy New Stamp
|
||||
</SwarmButton>
|
||||
</Form>
|
||||
)}
|
||||
</Formik>
|
||||
Buy New Stamp
|
||||
</SwarmButton>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type { ReactElement } from 'react'
|
||||
import { ReactElement, useContext } from 'react'
|
||||
import TimerFlash from 'remixicon-react/TimerFlashFillIcon'
|
||||
import ExpandableElement from '../../components/ExpandableElement'
|
||||
import ExpandableList from '../../components/ExpandableList'
|
||||
import ExpandableListItem from '../../components/ExpandableListItem'
|
||||
import ExpandableListItemActions from '../../components/ExpandableListItemActions'
|
||||
import ExpandableListItemKey from '../../components/ExpandableListItemKey'
|
||||
import StampExtensionModal from '../../components/StampExtensionModal'
|
||||
import { Context } from '../../providers/Settings'
|
||||
import { EnrichedPostageBatch } from '../../providers/Stamps'
|
||||
import { secondsToTimeString } from '../../utils'
|
||||
import { getHumanReadableFileSize } from '../../utils/file'
|
||||
@@ -13,7 +17,11 @@ interface Props {
|
||||
}
|
||||
|
||||
function StampsTable({ postageStamps }: Props): ReactElement | null {
|
||||
if (postageStamps === null) return null
|
||||
const { beeDebugApi } = useContext(Context)
|
||||
|
||||
if (!postageStamps || !beeDebugApi) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<ExpandableList label="Postage Stamps" defaultOpen>
|
||||
@@ -38,7 +46,16 @@ function StampsTable({ postageStamps }: Props): ReactElement | null {
|
||||
<ExpandableListItem label="Label" value={stamp.label} />
|
||||
<ExpandableListItem label="Usable" value={stamp.usable ? 'yes' : 'no'} />
|
||||
<ExpandableListItem label="Exists" value={stamp.exists ? 'yes' : 'no'} />
|
||||
<ExpandableListItem label="Immutable" value={stamp.immutableFlag ? 'yes' : 'no'} />
|
||||
<ExpandableListItem label="Purchase Block Number" value={stamp.blockNumber} />
|
||||
<ExpandableListItemActions>
|
||||
<StampExtensionModal
|
||||
label="Topup & Dilute"
|
||||
icon={<TimerFlash size="1rem" />}
|
||||
beeDebug={beeDebugApi}
|
||||
stamp={stamp.batchID}
|
||||
/>
|
||||
</ExpandableListItemActions>
|
||||
</>
|
||||
}
|
||||
>
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
Peer,
|
||||
Topology,
|
||||
} from '@ethersphere/bee-js'
|
||||
import { createContext, ReactChild, ReactElement, useContext, useEffect, useState } from 'react'
|
||||
import { ReactChild, ReactElement, createContext, useContext, useEffect, useState } from 'react'
|
||||
import semver from 'semver'
|
||||
import PackageJson from '../../package.json'
|
||||
import { useLatestBeeRelease } from '../hooks/apiHooks'
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Bee, BeeDebug } from '@ethersphere/bee-js'
|
||||
import { providers } from 'ethers'
|
||||
import { createContext, ReactNode, ReactElement, useEffect, useState } from 'react'
|
||||
import { useGetBeeConfig } from '../hooks/apiHooks'
|
||||
import { ReactElement, ReactNode, createContext, useEffect, useState } from 'react'
|
||||
import { DEFAULT_BEE_API_HOST, DEFAULT_BEE_DEBUG_API_HOST, DEFAULT_RPC_URL } from '../constants'
|
||||
import { useGetBeeConfig } from '../hooks/apiHooks'
|
||||
|
||||
const LocalStorageKeys = {
|
||||
providerUrl: 'json-rpc-provider',
|
||||
@@ -18,7 +18,7 @@ interface ContextInterface {
|
||||
isDesktop: boolean
|
||||
desktopUrl: string
|
||||
rpcProviderUrl: string
|
||||
rpcProvider: providers.JsonRpcProvider
|
||||
rpcProvider: providers.JsonRpcProvider | null
|
||||
cors: string | null
|
||||
dataDir: string | null
|
||||
ensResolver: string | null
|
||||
@@ -42,7 +42,7 @@ const initialValues: ContextInterface = {
|
||||
desktopUrl: window.location.origin,
|
||||
setAndPersistJsonRpcProvider: async () => {}, // eslint-disable-line
|
||||
rpcProviderUrl: '',
|
||||
rpcProvider: new providers.JsonRpcProvider(''),
|
||||
rpcProvider: null,
|
||||
cors: null,
|
||||
dataDir: null,
|
||||
ensResolver: null,
|
||||
|
||||
+3
-6
@@ -1,4 +1,4 @@
|
||||
import { BatchId, BeeDebug, BeeResponseError, PostageBatch } from '@ethersphere/bee-js'
|
||||
import { BatchId, BeeDebug, PostageBatch } from '@ethersphere/bee-js'
|
||||
import { decodeCid } from '@ethersphere/swarm-cid'
|
||||
import { BigNumber } from 'bignumber.js'
|
||||
import { BZZ_LINK_DOMAIN } from '../constants'
|
||||
@@ -258,11 +258,8 @@ async function waitForStamp(
|
||||
const stamp = await beeDebug.getPostageBatch(batchId)
|
||||
|
||||
if (stamp[field]) return stamp
|
||||
} catch (e) {
|
||||
// TODO: Workaround for https://github.com/ethersphere/bee/issues/3300
|
||||
if ((e as BeeResponseError).message !== 'Bad Request: cannot get batch') {
|
||||
throw e
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
await sleepMs(pollingFrequency)
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { Bee, Utils } from '@ethersphere/bee-js'
|
||||
import { loadAllNodes, MantarayNode, MetadataMapping, Reference } from 'mantaray-js'
|
||||
|
||||
interface ValueNode extends MantarayNode {
|
||||
getEntry: Reference
|
||||
}
|
||||
|
||||
/**
|
||||
* The ASCII code of the character `/`.
|
||||
*
|
||||
* This prefix of the root node holds metadata such as the index document.
|
||||
*/
|
||||
const INDEX_DOCUMENT_FORK_PREFIX = '47'
|
||||
|
||||
export class ManifestJs {
|
||||
private bee: Bee
|
||||
|
||||
constructor(bee: Bee) {
|
||||
this.bee = bee
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests whether a given Swarm hash is a valid mantaray manifest
|
||||
*/
|
||||
public async isManifest(hash: string): Promise<boolean> {
|
||||
try {
|
||||
const data = await this.bee.downloadData(hash)
|
||||
const node = new MantarayNode()
|
||||
node.deserialize(data)
|
||||
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves `website-index-document` from a Swarm hash, or `null` if it is not present
|
||||
*/
|
||||
public async getIndexDocumentPath(hash: string): Promise<string | null> {
|
||||
const metadata = await this.getRootSlashMetadata(hash)
|
||||
|
||||
if (!metadata) {
|
||||
return null
|
||||
}
|
||||
|
||||
return metadata['website-index-document'] || null
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves all paths with the associated hashes from a Swarm manifest
|
||||
*/
|
||||
public async getHashes(hash: string): Promise<Record<string, string>> {
|
||||
const data = await this.bee.downloadData(hash)
|
||||
const node = new MantarayNode()
|
||||
node.deserialize(data)
|
||||
await loadAllNodes(this.load.bind(this), node)
|
||||
const result = {}
|
||||
this.extractHashes(result, node)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves an arbitrary Swarm feed manifest to its latest update reference.
|
||||
* @returns `/bzz` root manifest hash, or `Promise<null>` if hash is not a feed manifest
|
||||
* @throws in case of network errors or bad input
|
||||
*/
|
||||
public async resolveFeedManifest(hash: string): Promise<string | null> {
|
||||
const metadata = await this.getRootSlashMetadata(hash)
|
||||
|
||||
if (!metadata) {
|
||||
return null
|
||||
}
|
||||
|
||||
const owner = metadata['swarm-feed-owner']
|
||||
const topic = metadata['swarm-feed-topic']
|
||||
|
||||
if (!owner || !topic) {
|
||||
return null
|
||||
}
|
||||
|
||||
const reader = this.bee.makeFeedReader('sequence', topic, owner)
|
||||
const response = await reader.download()
|
||||
|
||||
return response.reference
|
||||
}
|
||||
|
||||
private async getRootSlashMetadata(hash: string): Promise<MetadataMapping | null> {
|
||||
const data = await this.bee.downloadData(hash)
|
||||
const node = new MantarayNode()
|
||||
node.deserialize(data)
|
||||
|
||||
if (!node.forks) {
|
||||
return null
|
||||
}
|
||||
const fork = node.forks[INDEX_DOCUMENT_FORK_PREFIX]
|
||||
|
||||
if (!fork) {
|
||||
return null
|
||||
}
|
||||
const metadataNode = fork.node
|
||||
|
||||
if (!metadataNode.IsWithMetadataType()) {
|
||||
return null
|
||||
}
|
||||
const metadata = metadataNode.getMetadata
|
||||
|
||||
if (!metadata) {
|
||||
return null
|
||||
}
|
||||
|
||||
return metadata
|
||||
}
|
||||
|
||||
private extractHashes(result: Record<string, string>, node: MantarayNode, prefix = ''): void {
|
||||
if (!node.forks) {
|
||||
return
|
||||
}
|
||||
for (const fork of Object.values(node.forks)) {
|
||||
const path = prefix + this.bytesToUtf8(fork.prefix)
|
||||
const childNode = fork.node
|
||||
|
||||
if (this.isValueNode(childNode, path)) {
|
||||
result[path] = Utils.bytesToHex(childNode.getEntry)
|
||||
}
|
||||
|
||||
if (childNode.isEdgeType()) {
|
||||
this.extractHashes(result, childNode, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private load(reference: Uint8Array) {
|
||||
return this.bee.downloadData(Utils.bytesToHex(reference))
|
||||
}
|
||||
|
||||
private bytesToUtf8(bytes: Uint8Array): string {
|
||||
return new TextDecoder('utf-8').decode(bytes)
|
||||
}
|
||||
|
||||
private isValueNode(node: MantarayNode, path: string): node is ValueNode {
|
||||
return !this.isRootSlash(node, path) && node.isValueType() && typeof node.getEntry !== 'undefined'
|
||||
}
|
||||
|
||||
private isRootSlash(node: MantarayNode, path: string): boolean {
|
||||
return path === '/' && node.IsWithMetadataType()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user