# Приклади

> Готові приклади для API NeuroChain на локальній ноді — curl, JavaScript і Python для стану, блоків, акаунтів, крана, підписаних переказів, аналізу контрактів і живих подій WebSocket, зі справжніми відповідями.

Source: https://docs.nro.world/uk/reference/examples

Усі приклади працюють з **локальним стеком** (див. [Запуск ноди](/uk/operate/node)):

```bash
export NODE_RPC=http://localhost:9933
export GATEWAY=http://localhost:3000
```

Відповіді нижче отримано в тестовій мережі з одним валідатором; ваші висоти, хеші й адреси будуть іншими.

## curl

### Стан ноди

```bash
curl -s "$NODE_RPC/health"
```

```json
{"status":"ok","height":561,"round":0,"mempool":0,"peers":0,"tps":0,"total_txs":16,
 "validator_count":1,"bft_quorum":1,"bft_ready":false,"finality_ms":12.4}
```

`bft_ready` дорівнює `false`, якщо валідаторів менше 7. `finality_ms` поки не вимірюється; не покладайтеся на нього.

### Останній блок

```bash
curl -s "$GATEWAY/api/v1/blocks?limit=1"
```

```json
{"blocks":[{"height":562,"hash":"0x64555fa2…","parent_hash":"0x29a83fe0…",
  "proposer":"neuro:node-1.node","round":0,"shard":0,"tx_count":0,
  "tx_root":"0x0000…","state_root":"0xae62d247…","timestamp":1791201937625}],
 "total":562,"limit":1,"offset":0,"has_more":true}
```

### Акаунт

```bash
curl -s "$GATEWAY/api/v1/accounts/neuro:a231ca549778bdd.human"
```

```json
{"address":"neuro:a231ca549778bdd.human","type":"human","balance":50000000,"balance_human":"50",
 "nonce":0,"next_nonce":1,"tx_count":1,"shard":0,"is_contract":false,"verified":true,"custom_address":""}
```

### Кран (тестові мережі)

```bash
curl -s -X POST "$NODE_RPC/api/v1/faucet" -H 'Content-Type: application/json' \
  -d '{"address":"neuro:a231ca549778bdd.human","public_key":"<hex>"}'
```

```json
{"success":true,"status":"pending","address":"neuro:a231ca549778bdd.human",
 "amount":50000000,"amount_human":"50","block":24,"tx_hash":"0xa25f463d…",
 "note":"faucet applied on block commit"}
```

### Оцінка газу

```bash
curl -s "$NODE_RPC/api/v1/gas/estimate"
```

```json
{"base_fee":1,"gas_base_transfer":21,"gas_contract_call":50,"estimated_transfer":21,
 "estimated_transfer_human":"0.000021","estimated_contract":50,"estimated_contract_human":"0.00005",
 "nft_transfer_fee":100,"nft_transfer_fee_human":"0.0001","total_burned":0}
```

### Аналіз контракту

```bash
HEX=$(od -An -tx1 -v my_contract.wasm | tr -d ' \n')
curl -s -X POST "$NODE_RPC/api/v1/contracts/analyze" -H 'Content-Type: application/json' \
  -d "{\"bytecode_hex\":\"$HEX\"}"
```

```json
{"risk_score":0,"security_score":100,"safe":true,"ml_score":0.439,"model":"heuristic",
 "violations":[],"gas_estimate":34550}
```

### Читання контракту без транзакції

```bash
curl -s -X POST "$GATEWAY/api/v1/contracts/neuro:6d69004b47.app/call" -H 'Content-Type: application/json' \
  -d '{"function":"balance_of","args":{"address":"neuro:af6673a44550e1d.human"},"dry_run":true}'
```

```json
{"success":true,"dry_run":true,"contract":"neuro:6d69004b47.app","height":58,"gas_used":16047,
 "return_data":"{\"ok\":true,\"value\":250000000\u0000}","events":[],"error":null}
```

### Інші запити на читання

```bash
curl -s "$GATEWAY/api/v1/validators"
curl -s "$GATEWAY/api/v1/governance/params"
curl -s "$GATEWAY/api/v1/transactions/<hash>"
curl -s "$GATEWAY/api/v1/cross-shard/queue?limit=20&status=locked"
curl -s "$GATEWAY/api/v1/vault/<vault address>/config"
```

Запити на запис потребують підписів ML-DSA-65, яких `curl` створити не може — використовуйте JavaScript нижче або [SDK](/uk/build/sdk).

## JavaScript: підписаний переказ

Використовує криптомодуль WASM гаманця (`neurochain-web/src/wasm`) і dApp SDK. Перевірено з Node.js 22.

```js
import fs from 'node:fs'
import * as crypto from './wasm/neuro_wasm_crypto.js'
import { NeuroChain, toRaw } from './sdk/neurochain.js'

crypto.initSync({ module: fs.readFileSync('./wasm/neuro_wasm_crypto_bg.wasm') })

const GATEWAY = 'http://localhost:3000'
const nc = new NeuroChain({ gateway: GATEWAY, crypto })
const wallet = await nc.walletFromMnemonic(process.env.WORDS)   // ваші 24 слова

const to = 'neuro:af6673a44550e1d.human'
const value = Number(toRaw('1.5'))
const nonce = await nc.nextNonce(wallet.address)
const { base_fee } = await nc.gasEstimate()

const res = await fetch(GATEWAY + '/api/v1/transactions', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    from: wallet.address, to, value, nonce,
    gas_price: Math.ceil(base_fee * 1.5),
    ...wallet.sign(to, value, nonce),
  }),
}).then(r => r.json())
console.log(res)
```

```json
{"tx_hash":"0x3752a548…","status":"pending","estimated_block":26,
 "sender_balance":48500000,"receiver_balance":1500000,
 "sentinel_score":0.6228,"sentinel_category":"elevated",
 "sentinel_warning":"Transaction accepted but flagged as anomalous"}
```

За мить `GET /api/v1/transactions/0x3752a548…` повертає `"status":"confirmed"`, `"gas":21`, `"fee":42`, `"fee_human":"0.000042"` (21 одиниця газу × ціна газу 2).

## JavaScript: живі події

```js
const ws = new WebSocket('ws://localhost:3000/ws')
ws.onopen = () => ws.send(JSON.stringify({ type: 'subscribe_balance', address: 'neuro:a231ca549778bdd.human' }))
ws.onmessage = (e) => {
  const m = JSON.parse(e.data)
  if (m.type === 'new_block') console.log('block', m.data.height)
  if (m.type === 'balance')   console.log('balance', m.balance_human)
}
```

## Python

```python
import requests

NODE = "http://localhost:9933"
GW = "http://localhost:3000"

def balance(address):
    return requests.get(f"{GW}/api/v1/accounts/{address}").json()["balance_human"]

def latest_block():
    return requests.get(f"{GW}/api/v1/blocks", params={"limit": 1}).json()["blocks"][0]

def analyze(path):
    hexcode = open(path, "rb").read().hex()
    return requests.post(f"{NODE}/api/v1/contracts/analyze", json={"bytecode_hex": hexcode}).json()

print(latest_block()["height"], analyze("my_contract.wasm")["security_score"])
```
