# Now Trade Meta — funded engine, Bitcoin funding and data products

Release 0.7.0. This is an implemented **testnet** extension of the existing NowMeta explorer, markets and treasury. The private Sites website is the interface; its live data, Bitcoin adapter, keeper and chain require the VPS installation. No mainnet, real Bitcoin acceptance, external customers or independent security audit has been established.

## What this adds

| Component | Implemented behavior | Operating requirement |
|---|---|---|
| Funded engine | Native NMETA collateral, resting buy/sell limits, exact whole-order fills, optional stop loss and take profit, hourly expiries, withdrawal credits | New engine contract, council-approved markets, independent price reporters and funded counterparties |
| Risk controls | Per-position, wallet, market and global collateral limits; maximum 5× reference exposure; fresh-price gates; jump circuits; reporter emergency pause | Council configuration, monitoring and incident procedures |
| Market reference | Confirmed explorer history, five-minute time weighting, minimum activity and dispersion gates, reproducible evidence | Synced indexer and independently operated reporter databases |
| Bitcoin funding | Locked amount/rate/spread quote, BTCPay testnet invoice, independent Bitcoin-node verification, council NMETA delivery | Testnet BTCPay, Bitcoin node, rate publisher, NMETA reserve, council |
| Data products | Developer/exchange keys, prepaid licenses, metering, REST and five-second SSE snapshots, canonical execution events | Operator billing and license issuance; capacity and service-level commitments separately reviewed |
| Audit | Contract events, reorganization records, funding/license/access events, append-only hash chain, Ed25519 checkpoint exports | Off-server checkpoint retention and independent verification |

The original v0.6 expiry contract remains unchanged. Its positions are not migrated. NFT collection rounds are added at `contracts.nftRounds`. The new engine lives at `contracts.tradeEngine` and has its own escrow and credits. Thirteen top-level entries exist in a fresh v0.7 ecosystem manifest.

## How funded orders execute

1. The council approves a registered Studio/Pump token and sets its risk policy. No markets start enabled.
2. Reporters independently reconstruct the same confirmed explorer mark, sign its EIP-712 payload and submit a quorum bundle. The domain binds signatures to this engine and chain ID 20261025.
3. A maker locks margin plus a 0.1% **margin-based** fee. The buy limit is a maximum acceptable entry; the sell limit is a minimum acceptable entry. Orders cannot fill when the price is stale, the market is disabled or a circuit is halted.
4. A different wallet funds the opposite leg with equal margin and fee. It accepts the current signed price and mark sequence. Browser fills require that exact price; a changed sequence forces a new review. There is no order matching daemon or partial fill. The optional keeper handles exits and expired cancellations, not counterparty funding.
5. A subsequent accepted mark can trigger either participant's stop or target. The **entire bilateral position** closes and pays both parties. Participants can update or remove their own brackets. An already-crossed revised bracket can make an exit immediately eligible on the current post-fill mark.
6. An on-chain eligible close is permissionless. The keeper, a trader, or any third party can submit it. New-risk pause does not prevent cancellation, eligible exits or withdrawal. A price circuit does prevent use of suspect live marks until council recovery.

Payout uses the executed entry, not the limit: `change = min(margin, floor(margin × leverage × abs(exit − entry) / entry))`. The winning side receives margin plus change; the other receives margin minus change. Both payouts total twice the margin. Gains and losses are capped at one margin; fees and gas are additional. This is a fully funded, capped bilateral derivative, **not** a perpetual product, broker-provided credit, liquidation engine or prop-firm evaluation program.

Example: each side posts 10 NMETA and a 0.01 NMETA fee, at entry 2 with 2× exposure. A long target at 2.2 is crossed by an accepted mark at 2.3. The long receives 13 NMETA and the short 7; treasury receives 0.02 in matched fees. The target is a trigger, not a guaranteed execution price.

At an hourly UTC expiry, the engine stores the first non-halted quorum mark whose observation falls in the first 120 seconds of that hour. That snapshot is immutable for this expiry and remains usable after later marks or long delays. It is a short post-expiry observation window, not an assertion of an exact exchange price at the hour. If no eligible expiry snapshot is recorded, either party can recover margin after expiry plus 24 hours; matched fees remain paid. Stops can be missed between accepted marks or keeper cycles. Outages, price jumps, insufficient history and council delays can prevent timely execution.

## Explorer-based reference and risk policy

`GET /api/engine/risk/TOKEN` constructs a report from registered spot execution events. Defaults: five confirmations, five-minute window, at least five trades, three distinct trader addresses, one NMETA aggregate native volume, a fresh end trade, an anchor trade within 60 seconds before the window, and no more than 15% high/low dispersion relative to the time-weighted mean. A truncated window is rejected. All price and financial arithmetic uses integers. Evidence includes genesis, anchor block/hash, source transactions and parameters. The sequence is the confirmed anchor block height.

Distinct addresses are not independent people. Wash trading, collusion, thin pools and a compromised reporter quorum can still produce misleading marks. The contract checks signatures, freshness and circuit bounds; it does not independently verify explorer database contents. These defaults are test settings, not a defensible production market-admission policy. A chain reorganization can invalidate source evidence; operators must halt, reconcile and wait for a fresh confirmed sequence. Existing signed marks cannot be erased by the API.

On-chain caps start at 100,000 NMETA globally and 10,000 per wallet. These are limits on committed collateral (including an unmatched reserved fee), not notional exposure. Per-market limits and maximum position size must be configured. Policies can reduce limits below current exposure without seizing funds; new risk remains blocked until exposure falls. Maximum leverage is 5×. A jump beyond the configured 1–30% band stores the signed mark but latches the circuit. Only council review of the exact current sequence clears it. Any fixed reporter can immediately pause new risk. Council quorum and the existing two-day delay govern configuration and recovery. Reporters are fixed at deployment; use a reviewed successor deployment if they need replacement.

## Install or upgrade on Hostinger VPS

First follow `HOSTINGER_VPS_RUNBOOK.md`. Back up existing runtime data and keys. Never run `vps:init` on an existing network. Install this source package, run `npm ci`, `npm run compile`, and `npm run build` with Node 24.22.1. Existing `.runtime` files are intentionally excluded from the ZIP.

For a fresh v0.7 staging installation, the normal `bash ops/run.sh deploy` includes all three new contracts. For an existing v0.6 installation, build the new image and run the additive deployer:

```bash
bash ops/run.sh build
docker compose --env-file .runtime/vps/compose.env -f ops/compose.yaml run --rm deployer node scripts/deploy-engine.mjs
bash ops/run.sh up
```

The deployer preserves prior addresses and writes `ecosystem-before-engine.json` plus `engine-deployment-progress.json` before updating the manifest. Never delete a journal to retry blindly: inspect transaction receipts first. It captures the current treasury members as the fixed reporter committee. The testnet chain, genesis and runtime hashes are checked. After restart, load the updated manifest in Network operations and open **Funded engine**. The indexer backfills engine events in 50-block batches; a batch of 1,000 or more logs fails closed and needs a reviewed smaller batch.

Use **Risk & audit → Prepare a council action** to propose market policy. Example arguments (replace the token; all amounts are wei):

```json
["0xYOUR_TOKEN", {"enabled":true,"maxLeverage":2,"deviationBps":1500,"maxMargin":"10000000000000000000","cap":"100000000000000000000"}]
```

Review/approve/execute the proposal in Treasury council. `setRisk` arguments are `[pauseBoolean, globalCapWei, walletCapWei]`; `resume` arguments are `[token, reviewedSequence]`. The original council delay applies. Initial policy and circuit changes are not silently executed during deployment.

### Price reporting and keeper

Each reporter must have its own trusted explorer database and private key. The API hosts no reporter private keys. Use these commands on each reporter host; paths are examples, not credentials:

```bash
export NOWMETA_ENGINE_DB=/path/to/explorer.sqlite
export NOWMETA_DEPLOYMENT_FILE=/path/to/ecosystem-deployment.json
export NOWMETA_INTERNAL_RPC=https://your-reviewed-rpc.example
node scripts/engine-ops.mjs mark-report 0xTOKEN > report.json
node scripts/engine-ops.mjs mark-sign report.json /secure/reporter.json > signature.json
```

Distribute the public report to the other reporters. `mark-sign` reconstructs evidence at the report's anchor from that reporter's local database and refuses disagreement. The key file contains a `privateKey` field; protect it with mode 0600 and separate accounts. Combine at least the threshold signatures into a JSON array. The relayer verifies matching domains, genesis and marks; the contract verifies authorized, unique, sorted signers:

```bash
node scripts/engine-ops.mjs mark-submit signatures.json /secure/relayer.json
NOWMETA_EXECUTE_TESTNET=yes node scripts/engine-ops.mjs mark-submit signatures.json /secure/relayer.json
```

The first command is a dry run. Reports expire within 120 seconds of their observation; signing and submission must complete in that window. Independent reporter scheduling and signature collection are operator integrations, not an included central oracle daemon. Monitor fresh sequence growth and expiry snapshots.

Keeper dry run:

```bash
node scripts/engine-keeper.mjs --once
```

For execution set `NOWMETA_KEEPER_KEY_FILE` to a small-balance dedicated testnet signer file and `NOWMETA_EXECUTE_TESTNET=yes`. The keeper scans 50 global orders per cycle, submits up to five transactions per cycle and caps estimated fees at 0.1 NMETA per cycle. It is not a daily spending limit. A journal records submitted hashes; uncertainty stops the process and requires receipt reconciliation. Large order counts need multiple independently monitored keepers and load testing; this bounded scanner offers no latency guarantee.

An optional `ops/engine.yaml` overlay provides a keeper container and mounts server-side funding configuration. Create `.runtime/vps/engine-secrets` and `.runtime/vps/keeper` with the configured container UID/GID. Copy `ops/funding.example.json` to `engine-secrets/funding.json`, keeping `enabled:false` until configured. Store the keeper key as `engine-secrets/keeper.json`. Do not commit these files.

```bash
docker compose --env-file .runtime/vps/compose.env -f ops/compose.yaml -f ops/engine.yaml up -d --build api web
NOWMETA_EXECUTE_TESTNET=yes docker compose --env-file .runtime/vps/compose.env -f ops/compose.yaml -f ops/engine.yaml --profile engine up -d --build keeper
```

When `engine-secrets/funding.json` exists, `ops/run.sh` and `ops/backup.sh` include the engine overlay automatically, so consistent backups also stop a running keeper. All of `.runtime/vps`, including engine secrets and journals, is encrypted in the backup.

The keeper does not restart itself after uncertainty. Investigate the journal before manually restarting it.

## Bitcoin → NMETA conversion

This release intentionally rejects mainnet Bitcoin destinations because NMETA here is a testnet. Funding is a treasury inventory sale: BTC stays in the configured BTCPay wallet; existing NMETA is credited from `NowBitcoinSettlement`. It is not an atomic cross-chain swap, bridge or automatic external-exchange trade.

1. Configure a **testnet** BTCPay store with invoice creation/read permissions only, an independent synchronized Bitcoin test-network node with read-only RPC access, and a scoped webhook secret. The Bitcoin node needs transaction lookup capability (`txindex` or equivalent availability). No spending RPC or BTC private key is required by this adapter.
2. Fund the settlement contract with test NMETA using the treasury's native-transfer proposal. `available()` is balance minus allocated credits. Invoice creation also reserves pending quote amounts in the service database, and caps simultaneous reservations at 20.
3. Populate a reviewed rate in `funding.json`: `nmetaWeiPerBtc`, Unix `asOf`, traceable `source`, and `spreadBps` (0–1,000). The quote service rejects rates older than 60 seconds. There is no fabricated NMETA/USD rate. A rate publisher must obtain an executable, defensible treasury quote and atomically replace the configuration. Setting a rate is not evidence of a liquid external market.
4. Quote formula: `floor(satoshis × NMETAweiPerBTC × (10,000 − spreadBps) / 100,000,000 / 10,000)`. Quotes last ten minutes. Amounts are limited to 0.0001–0.01 test BTC. The receipt is a bearer recovery secret; retain it privately. API keys and receipts never appear in URLs.
5. Create an invoice only after the customer reviews the quote. BTCPay uses on-chain BTC, zero payment tolerance and `LowSpeed` (six confirmations). Before exposing checkout, the adapter checks the test-network Bitcoin node and the provider's testnet receiving address.
6. Configure a BTCPay webhook to `https://YOUR_SITE/api/bitcoin/webhook` using the same secret. The service verifies HMAC against raw bytes, then fetches invoice state independently. It verifies invoice identity, metadata, exact amount, normal settled state, payment time and every unique outpoint. Each outpoint must match the destination/value and have at least six confirmations from the Bitcoin node. A signed webhook alone never creates NMETA credits.
7. Missing/partial/late/extra/invalid or uncertain payments are held for review. No automatic refund or BTC spend is implemented. Repeated requests do not create duplicate invoices or credits. An uncertain invoice POST stays in `creating`; reconcile it with the provider using the quote order ID before any retry. Invoice IDs are never guessed or regenerated. Expired invoices with no payments can release their reservation after reconciliation.
8. On the server, prepare a verified delivery proposal:

```bash
NOWMETA_ENGINE_DB=/path/to/explorer.sqlite NOWMETA_FUNDING_CONFIG=/secure/funding.json node scripts/engine-ops.mjs bitcoin-proposal QUOTE_ID
```

This rechecks confirmations and outputs target, calldata, recipient, amount, invoice hash and evidence. In the site's council action form, select **Deliver verified Bitcoin conversion** and supply `[invoiceHash, recipient, amountWei, evidenceHash]`. The council must review those exact values, approve and execute after its existing delay. The settlement contract refuses duplicate invoice hashes and underfunded deliveries. It trusts council verification; it does not verify Bitcoin consensus on-chain. The customer then claims the native NMETA credit. This is deliberately not instant conversion.

A reserve cannot be reused for new invoices while pending quotes reserve it. Recheck completed deliveries via the customer's receipt status to release the off-chain pending reservation. Lost receipts require a separately authenticated support process. Keep funding database, invoice records and reserve state in reconciled backups. Never send real BTC to this installation. Production BTC acceptance needs a production NMETA chain and a separately reviewed custody, pricing, refund and conversion service.

## Selling data access

Commercial products cover normalization, delivery, usage rights and support; public blockchain data itself remains public. Developer and exchange plans expose the same registered venue data with different quotas. Prices are operator-selected per license, not invented subscription prices. Billing collection, negotiated terms and customer verification are outside this release.

Fill `ops/feed-license.example.json` with a non-sensitive customer reference, plan (`developer` or `exchange`), expiry Unix timestamp, verified payment/contract reference, price and currency (`NMETA`, `BTC` or `USD`). Then run on the API host:

```bash
NOWMETA_ENGINE_DB=/path/to/explorer.sqlite node scripts/engine-ops.mjs license-issue paid-license.json
NOWMETA_ENGINE_DB=/path/to/explorer.sqlite node scripts/engine-ops.mjs license-revoke LICENSE_ID
```

Issuance prints the random API key once; the database stores only its SHA-256 hash. Deliver the key securely yourself. Revocation takes effect on the next request/stream frame. Developer limits: 60 calls/minute, 10,000/day, one stream. Exchange limits: 600/minute, 1,000,000/day, five streams. Stream frames count toward quotas. Limits persist across service restarts. An outer IP rate limiter can impose a tighter shared limit; review it and load-test before promising exchange throughput.

Use `Authorization: Bearer YOUR_KEY`:

- `GET /api/pro/v1/snapshot?token=TOKEN` — market snapshot with chain/genesis/block hash, current canonical engine events and index positions.
- `GET /api/pro/v1/candles?token=TOKEN&interval=1m&limit=100&before=UNIX` — bounded historical OHLC/volume.
- `GET /api/pro/v1/trades?afterBlock=0&offset=0&token=TOKEN` — 100 spot trades per page; next offset supplied.
- `GET /api/pro/v1/engine-events?afterBlock=0&offset=0` — 100 canonical funded-engine/settlement events per page; consumers reconstruct offers, fills and exits using the published ABIs.
- `GET /api/pro/v1/stream?token=TOKEN` — SSE full snapshots every five seconds. Connections last five minutes; clients reconnect with their header. A frame contains bounded current data, not every intervening event. Backfill REST to avoid losing events.

Every snapshot contains a block hash and explicit reorgability. SSE IDs are connection-local, not durable exactly-once cursors. On reconnect or branch change, replace the snapshot and backfill from a verified common ancestor, deduplicating `(transaction hash, log index)`; remove orphaned records. Block-offset pagination can change during reorg. No subsecond, globally distributed, FIX, WebSocket, external-exchange coverage or guaranteed SLA is claimed. Wallet secrets, funding receipts, customer identities and pledge data are never included in licensed feeds.

## Audit and recovery

The engine emits policy, circuit, order, bracket, close and withdrawal events. Bitcoin delivery emits a unique invoice hash and evidence hash. The indexer records canonical events and appends audit evidence; chain reorganizations append an orphaned-anchor record while canonical tables rewind. The hash-linked audit table rejects ordinary updates/deletes and verifies at service start. Service actions also record funding transitions, license activation/revocation and metered access. Rejected public requests are not all retained; use proxy/security logs for abuse analysis without logging secrets.

```bash
node scripts/engine-ops.mjs audit-verify
node scripts/engine-ops.mjs audit-export /secure/audit-events.jsonl
node scripts/engine-ops.mjs audit-keygen /offline/audit-signing.pem
node scripts/engine-ops.mjs audit-checkpoint /offline/audit-signing.pem > checkpoint.json
```

Checkpoint generation verifies every link, then signs sequence and tip hash with Ed25519. Store checkpoints and the public key off-server, ideally with independently controlled immutable retention. The signing command needs read access to a consistent database copy; do not put the private signing key on the internet-facing host. `services/audit.mjs` exposes `verifyCheckpoint` for independent verification. A local hash chain alone cannot prevent an administrator from rewriting the database, deleting its tail or replacing keys. Compare against independently retained checkpoints.

Prometheus metrics include engine index height, audit sequence and Bitcoin review queue size. Alert rules cover engine indexing lag and a persistent funding review queue; no notification receiver is configured by this package.

Daily reconciliation must compare contract balance with `totalEscrow + totalCredits`; on-chain orders with canonical indexed events; Bitcoin invoice outpoints and confirmations with quotes; pending conversion reservations with settlement reserve; and issued licenses with verified payment references. Halt new risk on stale marks, unexplained exposure, price circuits, missing event batches or an audit mismatch. Preserve withdrawal paths and evidence. Restore SQLite using a consistent backup (including WAL when applicable), then replay the chain and re-verify external deposits; copying a live `.sqlite` file alone is not a safe backup method.

## Validation and remaining work

See `SECURITY_AND_VALIDATION.md` and `validation-v07.json` for the exact executed tests and limits. The automated suite exercises funded collateral conservation, bracket exits, immutable expiry snapshots, timeout refunds, circuit/authority controls, invoice replay/confirmation/late-payment handling, audit tamper detection, licenses, REST and streaming revocation. Provider tests use fixtures; a real BTCPay/Bitcoin installation, Hostinger/Docker, installed-wallet signing and independent audit remain pending. Integration tests do not prove market safety, anonymity, production capacity or regulatory readiness.

Official references checked while implementing:

- BTCPay integration and webhook guidance: https://docs.btcpayserver.org/Developers/api/
- Instance-specific Greenfield API and schema: https://docs.btcpayserver.org/API/Greenfield/v1/ (use your instance's `/docs` and `/swagger/v1/swagger.json` for acceptance testing).
- BTCPay payment method model: https://github.com/btcpayserver/btcpayserver/blob/master/BTCPayServer.Client/Models/InvoicePaymentMethodDataModel.cs
- OpenZeppelin EIP-712 and signature utilities: https://docs.openzeppelin.com/contracts/5.x/api/utils#EIP712

## NFT launches and extra rounds

NFT studio creates ERC-721 collections with a fixed supply cap and royalty setting. The collection owner mints NFTs within that cap; owners can list minted NFTs on the marketplace. Additional promotional rounds are now supported by a separate `NowNFTRounds` hub, included in the v0.7 additive deployer. It uses the same funnel editor, preserved roadmap/version history, round lifecycle, admin-set fee and encrypted free signup system as token rounds.

Select **Re-launch rounds → Campaign type → NFT collections**, then open Funnel studio. Enter an existing NFT studio collection address and connect its current owner wallet. Register the collection, customize the sales funnel, create the first or next round, and share its generated link. The link includes the NFT hub address; token and NFT project/round IDs cannot collide. Every round gets a distinct pledge scope and requires new consent. NFT mint/sale is a separate wallet-approved action; a promotion pledge does not buy an NFT or reserve one.

Collection ownership determines who can edit and manage NFT campaigns. A two-step ownership transfer changes campaign control only when the new owner accepts; the former owner then loses access. Existing public terms and historical versions remain preserved. A renounced collection has no manager. Fee exemptions follow the asset and can be changed only by treasury council. NFT round fees are administered separately from token round fees under **Treasury council**. The upgrade initializes the NFT round fee to the current token round fee; afterward they can differ.

More rounds do **not** reset supply, increase the NFT cap, mint automatically, reset prices, create liquidity or add NFT futures. Use a new collection if you need a different supply cap. Existing token/native campaigns and their signup records remain at their original hub.
