Skip to main content

Example: Find Existing Entities

This example demonstrates how to find existing atoms and triples to avoid creating duplicates.

SDK reads default to the mainnet GraphQL API. This flow both reads and writes on Intuition Testnet, so it configures the testnet API before its first lookup; optional atom amounts are additional tTRUST signal because the SDK fetches the required base cost automatically.

Complete Code​

import {
configureSdk,
intuitionTestnet,
getMultiVaultAddressFromChainId,
findAtomIds,
findTripleIds,
calculateAtomId,
calculateTripleId,
createAtomFromString,
createTripleStatement,
} from '@0xintuition/sdk'
import { API_URL_DEV } from '@0xintuition/graphql'
import { createPublicClient, createWalletClient, http, parseEther, toHex } from 'viem'
import { privateKeyToAccount } from 'viem/accounts'
import type { Hex } from 'viem'

async function main() {
// Setup
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`)
// SDK reads default to mainnet; keep reads paired with the testnet write chain.
configureSdk({ apiUrl: API_URL_DEV })

const publicClient = createPublicClient({
chain: intuitionTestnet,
transport: http(),
})
const walletClient = createWalletClient({
chain: intuitionTestnet,
transport: http(),
account,
})
const address = getMultiVaultAddressFromChainId(intuitionTestnet.id)

// 1. Find existing atoms
console.log('=== Finding Atoms ===\n')

const atomData = ['TypeScript', 'JavaScript', 'Python', 'Rust']

const atoms = await findAtomIds(atomData)
const missingAtomData = atomData.filter(
data => !atoms.some(atom => atom.data === data)
)

console.log('Results:')
atoms.forEach(atom => {
console.log(`βœ“ ${atom.data}: ${atom.term_id}`)
})
missingAtomData.forEach(data => {
console.log(`βœ— ${data}: not found`)
})

// 2. Create missing atoms
if (missingAtomData.length > 0) {
console.log(`\n=== Creating ${missingAtomData.length} Missing Atoms ===\n`)

for (const data of missingAtomData) {
const created = await createAtomFromString(
{ walletClient, publicClient, address },
data,
parseEther('0.01')
)
atoms.push({ data, term_id: created.state.termId })
console.log(`βœ“ Created: ${data}`)
}
}

// 3. Find existing triples
console.log('\n=== Finding Triples ===\n')

// Get atom IDs
const tsId = atoms.find(a => a.data === 'TypeScript')?.term_id as Hex
const jsId = atoms.find(a => a.data === 'JavaScript')?.term_id as Hex

if (!tsId || !jsId) {
throw new Error('Missing required atoms')
}

// Create predicate
const compilesTo = await createAtomFromString(
{ walletClient, publicClient, address },
'compilesTo'
)

// Check if triple exists
const tripleCombinations: Array<[Hex, Hex, Hex]> = [
[tsId, compilesTo.state.termId, jsId]
]

const triples = await findTripleIds(
account.address,
tripleCombinations
)

const tripleExists = triples[0]?.term_id

if (tripleExists) {
console.log('βœ“ Triple already exists:', tripleExists)
} else {
console.log('βœ— Triple not found, creating...')

const triple = await createTripleStatement(
{ walletClient, publicClient, address },
{
args: [
[tsId],
[compilesTo.state.termId],
[jsId],
[parseEther('0.1')],
],
value: parseEther('0.1'),
}
)

console.log('βœ“ Triple created:', triple.state[0].args.termId)
}

// 4. Calculate IDs offline
console.log('\n=== Offline ID Calculation ===\n')

const calculatedAtomId = calculateAtomId(toHex('NewAtom'))
console.log('Predicted atom ID for "NewAtom":', calculatedAtomId)

const calculatedTripleId = calculateTripleId(tsId, compilesTo.state.termId, jsId)
console.log('Predicted triple ID:', calculatedTripleId)

console.log('\nSuccess!')
}

main()
.then(() => process.exit(0))
.catch((error) => {
console.error('Error:', error)
process.exit(1)
})

See Also​