Overview
Utility functions provide reusable logic for common operations like data formatting, validation, file handling, and blockchain interactions.
DDO & Asset Utilities
isValidDid
Validate Ocean Protocol DID format.
Whether DID matches pattern did:op:[64-char-hex]
import { isValidDid } from '@utils/ddo'
const valid = isValidDid('did:op:1234567890abcdef...')
if (!valid) {
throw new Error('Invalid DID format')
}
getServiceByName
Extract a specific service from an asset DDO.
name
'access' | 'compute'
required
Service type to retrieve
Service object or undefined
import { getServiceByName } from '@utils/ddo'
const accessService = getServiceByName(asset, 'access')
const computeService = getServiceByName(asset, 'compute')
if (accessService) {
console.log('Provider URL:', accessService.serviceEndpoint)
console.log('Datatoken:', accessService.datatokenAddress)
}
getServiceById
Get a service by its ID.
import { getServiceById } from '@utils/ddo'
const service = getServiceById(asset, 'service-1')
isAddressWhitelisted
Check if an address has access to an asset based on credentials.
Ethereum address to check
Whether address can access the asset
import { isAddressWhitelisted } from '@utils/ddo'
import { useAccount } from 'wagmi'
function AccessCheck({ asset }) {
const { address } = useAccount()
const hasAccess = isAddressWhitelisted(asset, address)
if (!hasAccess) {
return <Alert state="error">You don't have access to this asset</Alert>
}
return <DownloadButton asset={asset} />
}
Time Utilities
mapTimeoutStringToSeconds
Convert human-readable timeout strings to seconds.
Timeout string (‘Forever’, ‘1 hour’, ‘1 day’, ‘1 week’, ‘1 month’, ‘1 year’)
Number of seconds (0 for ‘Forever’)
import { mapTimeoutStringToSeconds } from '@utils/ddo'
const seconds = mapTimeoutStringToSeconds('1 day')
// 86400
const forever = mapTimeoutStringToSeconds('Forever')
// 0
secondsToString
Convert seconds to human-readable duration string.
Human-readable string (e.g., ‘2 days’, ‘3 hours’)
import { secondsToString } from '@utils/ddo'
const duration = secondsToString(86400)
// '1 day'
const longDuration = secondsToString(2678400)
// '1 month'
Format numbers with locale-aware formatting.
Locale code (e.g., ‘en-US’, ‘de-DE’)
import { formatNumber } from '@utils/numbers'
const price = formatNumber(1234.5678, 'en-US', '2')
// '1,234.57'
const euro = formatNumber(1234.5678, 'de-DE', '2')
// '1.234,57'
compareAsBN
Compare two decimal numbers with BigNumber precision.
import { compareAsBN } from '@utils/numbers'
const hasEnough = compareAsBN('10.5', '10.0')
// true
const insufficient = compareAsBN('5.0', '10.0')
// false
getMaxDecimalsValidation
Generate regex for validating decimal places.
Maximum number of decimal places
Regular expression for validation
import { getMaxDecimalsValidation } from '@utils/numbers'
const validator = getMaxDecimalsValidation(2)
validator.test('10.99') // true
validator.test('10.999') // false
Provider Utilities
Functions for interacting with Ocean Protocol providers.
getFileInfo
Retrieve file metadata from a provider.
File URL, IPFS hash, or Arweave transaction ID
Storage type: ‘url’, ‘ipfs’, ‘arweave’, ‘graphql’, ‘smartcontract’
GraphQL query (for graphql type)
Contract ABI (for smartcontract type)
Chain ID (for smartcontract type)
Include file checksum in response
Array of file information objects
import { getFileInfo } from '@utils/provider'
// URL file
const urlInfo = await getFileInfo(
'https://example.com/data.csv',
'https://provider.oceanprotocol.com',
'url',
undefined,
[],
undefined,
undefined,
'GET',
true
)
// IPFS file
const ipfsInfo = await getFileInfo(
'QmXyz123...',
'https://provider.oceanprotocol.com',
'ipfs'
)
// Smart contract
const contractInfo = await getFileInfo(
'0x1234...', // contract address
'https://provider.oceanprotocol.com',
'smartcontract',
undefined,
[],
JSON.stringify(contractAbi),
1
)
getEncryptedFiles
Encrypt file information for DDO storage.
File object(s) to encrypt
import { getEncryptedFiles } from '@utils/provider'
const files = [{
type: 'url',
url: 'https://example.com/data.csv',
method: 'GET'
}]
const encrypted = await getEncryptedFiles(
files,
137,
'https://provider.oceanprotocol.com'
)
downloadFile
Download an asset file after purchase.
Custom parameters for compute
import { downloadFile } from '@utils/provider'
import { useSigner } from 'wagmi'
function DownloadButton({ asset }) {
const { data: signer } = useSigner()
const { address } = useAccount()
const handleDownload = async () => {
await downloadFile(
signer,
asset,
address,
asset.accessDetails.validOrderTx
)
}
return <Button onClick={handleDownload}>Download</Button>
}
checkValidProvider
Verify if a provider URL is valid and responsive.
Whether provider is valid
import { checkValidProvider } from '@utils/provider'
const isValid = await checkValidProvider('https://provider.oceanprotocol.com')
if (!isValid) {
console.error('Provider is not responding')
}
NFT Utilities
Generate NFT metadata with unique SVG artwork.
import { generateNftMetadata } from '@utils/nft'
const metadata = generateNftMetadata()
// {
// name: 'PX Data NFT',
// symbol: 'PX-NFT',
// description: '...',
// background_color: '141414',
// image_data: 'data:image/svg+xml,...',
// external_url: 'https://portal.pontus-x.eu'
// }
generateNftCreateData
Prepare data for NFT creation transaction.
Whether NFT can be transferred
Data for createNFT transaction
import { generateNftMetadata, generateNftCreateData } from '@utils/nft'
import { useAccount } from 'wagmi'
function CreateNFT() {
const { address } = useAccount()
const createNFT = async () => {
const metadata = generateNftMetadata()
const createData = generateNftCreateData(metadata, address, true)
// Use createData with Ocean Protocol SDK
}
}
decodeTokenURI
Decode NFT token URI to extract metadata.
import { decodeTokenURI } from '@utils/nft'
const tokenUri = 'data:application/json;base64,eyJuYW1lIjoi...'
const metadata = decodeTokenURI(tokenUri)
console.log(metadata.name, metadata.description)
Update NFT metadata and token URI on-chain.
nftMetadata
NftMetadata | undefined
required
New NFT metadata
Abort signal for cancellation
import { setNFTMetadataAndTokenURI, generateNftMetadata } from '@utils/nft'
import { useAbortController } from '@hooks/useAbortController'
import { useSigner, useAccount } from 'wagmi'
function UpdateNFT({ asset }) {
const { data: signer } = useSigner()
const { address } = useAccount()
const newAbortController = useAbortController()
const updateMetadata = async () => {
const metadata = generateNftMetadata()
const tx = await setNFTMetadataAndTokenURI(
asset,
address,
signer,
metadata,
newAbortController()
)
await tx.wait()
console.log('NFT updated')
}
return <Button onClick={updateMetadata}>Update NFT</Button>
}
General Utilities
sortAssets
Sort assets by a specific order of DIDs.
Array of DIDs in desired order
import { sortAssets } from '@utils/index'
const assets = [asset1, asset2, asset3]
const order = [asset2.id, asset1.id, asset3.id]
const sorted = sortAssets(assets, order)
getObjectPropertyByPath
Safely access nested object properties by path string.
Dot-notation path (e.g., ‘metadata.created’)
Property value or undefined
import { getObjectPropertyByPath } from '@utils/index'
const asset = {
metadata: {
name: 'My Dataset',
created: '2024-01-01'
}
}
const name = getObjectPropertyByPath(asset, 'metadata.name')
// 'My Dataset'
const missing = getObjectPropertyByPath(asset, 'metadata.missing.prop')
// undefined
fetchData
Simple fetch wrapper with error handling.
Response data or undefined on error
import { fetchData } from '@utils/fetch'
const data = await fetchData('https://api.example.com/data')
if (data) {
console.log('Success:', data)
}
Type Definitions
// NFT types
interface NftMetadata {
name: string
symbol: string
description: string
image?: string
external_url?: string
image_data?: string
background_color?: string
}
interface NftCreateData {
name: string
symbol: string
templateIndex: number
tokenURI: string
transferable: boolean
owner: string
}
// File types
interface FileInfo {
valid: boolean
contentLength?: string
contentType?: string
checksum?: string
}