Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
03cf850
docs: say plainly what HelloNear keeps, and call Freeze the kill switch
Lexirieru Nov 12, 2026
9037f98
feat(be): shop negotiation, payments CSV and a meta-transaction relayer
Lexirieru Nov 12, 2026
2cffd10
feat(sc): swarm auction for group buying, with a 20-buyer simulation
Lexirieru Nov 12, 2026
6ce5dc6
feat(engine): Agent Market quotes, one-round haggling, contract check…
Lexirieru Nov 12, 2026
74ca8b2
Merge remote-tracking branch 'origin/main' into feat/track-fit
Lexirieru Nov 12, 2026
b11c6bb
docs: README for Agent Market, haggling, contract check, payments CSV…
Lexirieru Nov 12, 2026
364aeae
feat(fe): Download CSV, and words and icons for haggling and the Agen…
Lexirieru Nov 12, 2026
41d5c77
fix(sc): swarm auction audit findings, and storage that was never cha…
Lexirieru Nov 12, 2026
852c1d0
Merge remote-tracking branch 'origin/main' into feat/track-fit
Lexirieru Nov 12, 2026
c7c12da
Merge remote-tracking branch 'origin/main' into feat/track-fit
Lexirieru Nov 12, 2026
f5a668e
fix(engine): haggle calls the tool before it talks, Payments warns on…
Lexirieru Nov 12, 2026
bf317c8
fix(fe): a 0.001 NEAR payment reads 0.001, not -0.00
Lexirieru Nov 12, 2026
79eb170
feat(engine): Agent Market finds the cheapest agent within the owner'…
Lexirieru Nov 12, 2026
1b969b1
docs: README for the swarm auction, Agent Market budgets and the roadmap
Lexirieru Nov 12, 2026
64c9278
fix(sc): swarm crate builds into its own target, so the reproducible …
Lexirieru Nov 12, 2026
1f940cd
fix(fe,be): Download CSV fetches the file, so it works across origins…
Lexirieru Nov 12, 2026
fb22143
docs: swarm auction live on testnet with a real round, and the Agent …
Lexirieru Nov 12, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion .github/workflows/sc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ jobs:
- run: rustup show active-toolchain || rustup toolchain install
- uses: Swatinem/rust-cache@v2
with:
workspaces: sc
workspaces: |
sc
sc/swarm
# The sandbox tests build the WASM through `cargo near` (cargo-near 0.22.0, see sc/CLAUDE.md). Pinned by checksum.
- name: Install cargo-near 0.22.0
working-directory: ${{ runner.temp }}
Expand All @@ -43,3 +45,13 @@ jobs:
- run: cargo test --locked --test test_registry
- run: cargo test --locked --test test_migration
- run: cargo clippy --locked --all-targets
# The swarm auction (sc/swarm, AI Swarms track): its own crate with its own target. The 20-buyer simulation takes
# ~2 min on a laptop, so it runs here too: it is the swarm's main proof.
- run: cargo test --locked --lib
working-directory: sc/swarm
- run: cargo test --locked --test test_round
working-directory: sc/swarm
- run: cargo test --locked --test simulation
working-directory: sc/swarm
- run: cargo clippy --locked --all-targets
working-directory: sc/swarm
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ The team uses macOS with **OrbStack** as the Docker runtime. Keep local services
| What | Account | Env |
|---|---|---|
| Mind registry contract (`sc/`), v0.3.0 | `hellonear-registry.testnet` | `REGISTRY_CONTRACT_ID`, `NEAR_NETWORK=testnet` |
| Swarm auction contract (`sc/swarm`), v0.1.0, source verified | `auction.hellonear-swarm.testnet`; agents are sub-accounts of `hellonear-swarm.testnet` (`coordinator`, `buyer-1..3`, `seller-1..2`), keys in Axel's keychain | none (no app reads it yet) |
| Demo Mind wallet (OutLayer, policy v2), owner `lin1er.testnet` | `83e05486fc84f7150a70fe44bdfc0692c19182cdd72af7721c9a8a2a511e98bd`; sub-wallet `skill-payments` `bcd8cdbd8b4038c12ab9076188d01f9e5238ff397c3c6097cec1488c6b16588b`. Replaced `0fdc9294…` on 8 Nov (its key was exposed; #70) | `OUTLAYER_API_KEY`, `OUTLAYER_SUB_SKILL_PAYMENTS` (James's `apps/be/.env`, never committed); hosted demo: `DEMO_OUTLAYER_API_KEY` |
| Try-out email inbox (AgentMail, Free plan, lexirieru's organization; not on chain) (#96) | `hellonear-demo@agentmail.to` (AgentMail `client_id` `hellonear-demo`), created 9 Nov | `AGENTMAIL_API_KEY` (Axel's local `apps/be/.env`, never committed), `DEMO_AGENTMAIL_INBOX`; not on the hosted demo yet |

Expand Down
80 changes: 61 additions & 19 deletions README.md

Large diffs are not rendered by default.

13 changes: 10 additions & 3 deletions apps/be/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,17 @@ DEMO_AGENTMAIL_INBOX=
# Optional: the testnet account a Mind pays for a Paid data report (#150). It must be on the paying wallet's address list
# (the demo wallet's, for try-outs). Empty: the shop answers 503 shop_not_configured
SHOP_PAY_TO=
# Optional, Best Price Buyer (#176): several sellers for the same items, account:multiplier separated by commas
# (e.g. a.testnet:1,b.testnet:0.8; price = base price x multiplier, up to 3 decimals). Each account must be on the paying
# wallet's address list. Empty: SHOP_PAY_TO is the only seller
# Optional, Best Price Buyer (#176): several sellers for the same items, account:multiplier[:floor] separated by commas
# (e.g. a.testnet:1,b.testnet:0.8:0.5; price = base price x multiplier, up to 3 decimals; floor = the share of its price a
# seller accepts in a negotiation, default 0.8). Each account must be on the paying wallet's address list. Empty:
# SHOP_PAY_TO is the only seller
SHOP_SELLERS=
# Optional, meta-transaction relayer (POST /v1/relay): a funded testnet account and one of its full-access keys
# (ed25519:...), created and funded by a person, never committed. It pays gas only for unequip_skill / set_wallet on
# REGISTRY_CONTRACT_ID (default hellonear-registry.testnet). Either one empty: the route answers 503 relay_not_configured
RELAYER_ACCOUNT_ID=
RELAYER_PRIVATE_KEY=
REGISTRY_CONTRACT_ID=
# Telegram (#168). The public API URL Telegram calls for webhooks (e.g. https://api.hellonear.xyz); leave it empty locally
# and set TELEGRAM_POLLING=true to poll getUpdates instead. TELEGRAM_API_URL is for tests (default https://api.telegram.org).
TELEGRAM_WEBHOOK_BASE=
Expand Down
7 changes: 5 additions & 2 deletions apps/be/CLAUDE.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions apps/be/bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

110 changes: 110 additions & 0 deletions apps/be/load/shop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// Short local load test of the paths the track work changed: the paid-data shop's price list and negotiation
// (`/internal/v1/shop/{item}?quotes=1` and `?seller=&offer=`, with the run's wallet token, as the engine calls them) and
// the payments CSV (`GET /v1/minds/{id}/payments.csv`, each Mind holding 200 payments with their runs' events). Every
// answer must be 200 with the right shape: an offer is accepted or countered at the expected price, and the CSV has one
// line per payment. Fake engine and fake OutLayer, local Postgres. Never point this at a public endpoint.
// Run: bun run load:shop (env: VUS=10, DURATION_S=10)
import type { AddressInfo } from 'node:net'
import { randomBytes } from 'node:crypto'
import { ENGINE_KEY, engine } from '../test/fake-engine.ts'
import { outlayerServer } from '../test/fake-outlayer.ts'

const VUS = Number(process.env.VUS ?? 10)
const DURATION_S = Number(process.env.DURATION_S ?? 10)
const PAYMENTS_PER_MIND = 200

await new Promise<void>((r) => engine.listen(0, r))
process.env.ENGINE_URL = `http://127.0.0.1:${(engine.address() as AddressInfo).port}`
process.env.ENGINE_API_KEY = ENGINE_KEY
await new Promise<void>((r) => outlayerServer.listen(0, r))
process.env.OUTLAYER_URL = `http://127.0.0.1:${(outlayerServer.address() as AddressInfo).port}`
process.env.NEAR_RPC_URL = `${process.env.OUTLAYER_URL}/rpc`
process.env.SHOP_PAY_TO = 'shop.testnet'
process.env.SHOP_SELLERS = 'shop.testnet:1,cheap.testnet:0.8:0.5,dear.testnet:1.3'
process.env.DATABASE_URL ??= 'postgresql://hellonear:hellonear-dev-only@localhost:55432/hellonear'
process.env.SECRETS_MASTER_KEY ??= randomBytes(32).toString('base64')

const { server } = await import('../src/server.ts')
const { migrate, pool, query } = await import('../src/db.ts')
const { newId, randomToken, sha256 } = await import('../src/crypto.ts')
const { issueWalletToken } = await import('../src/walletToken.ts')
await migrate()
await new Promise<void>((r) => server.listen(0, r))
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`

async function user() {
const id = newId('usr')
const token = randomToken()
await query('insert into users (id, near_account_id) values ($1, $2)', [id, `loadshop-${id}.testnet`])
await query(`insert into sessions (token_hash, user_id, expires_at) values ($1, $2, now() + interval '1 hour')`, [sha256(token), id])
const cookie = `hn_session=${token}`
const headers = { cookie, 'content-type': 'application/json', origin: 'http://localhost:3000' }
const mindId = (await (await fetch(`${base}/v1/minds`, { method: 'POST', headers, body: JSON.stringify({ templateId: 'payments-mind', name: 'Load shop' }) })).json()).mind.id as string
const w = await fetch(`${base}/v1/minds/${mindId}/wallet`, { method: 'POST', headers, body: '{}' })
if (w.status !== 201) throw new Error(`wallet: ${w.status} ${await w.text()}`)
// Payments, each made by a run whose events say who approved it (half by the owner's card, half by a rule).
const runId = `run_loadshop_${randomBytes(4).toString('hex')}`
await query(`insert into runs (id, mind_id, status) values ($1, $2, 'finished')`, [runId, mindId])
for (let i = 0; i < PAYMENTS_PER_MIND; i++) {
const pay = newId('pay')
await query(`insert into wallet_payments (id, mind_id, to_account, amount_yocto, status, tx_hash, message) values ($1, $2, 'shop.testnet', $3, $4, $5, $6)`,
[pay, mindId, (10n ** 21n * BigInt(i + 1)).toString(), i % 5 ? 'sent' : 'policy_denied', i % 5 ? randomBytes(22).toString('hex') : null, i % 5 ? null : 'Payment, "over" the limit, refused'])
const call = `c${i}`
const seq = i * 2
await query('insert into run_events (run_id, seq, type, payload, ts) values ($1, $2, $3, $4, now()), ($1, $5, $6, $7, now())', [runId, seq + 1,
i % 2 ? 'tool.approval_required' : 'tool.called', i % 2 ? { toolCallId: call } : { toolCallId: call, approvedBy: 'rule' }, seq + 2, 'tool.result', { toolCallId: call, result: { paymentId: pay } }])
}
return { cookie, mindId, walletToken: issueWalletToken(id, mindId) }
}

const users = await Promise.all(Array.from({ length: VUS }, user))
const latencies: Record<string, number[]> = { quotes: [], offer: [], csv: [] }
let errors = 0
const fail = (what: string) => { if (errors++ < 5) console.error(what) }
async function timed(name: string, f: () => Promise<boolean>) {
const t = performance.now()
try { if (!(await f())) fail(`${name}: wrong answer`) } catch (e) { fail(`${name}: ${e instanceof Error ? e.message : e}`) }
latencies[name].push(performance.now() - t)
}
// cheap.testnet (s2): price 0.0008, floor 0.0004. Offers and the answers they must get.
const OFFERS: [string, string, string][] = [['0.0004', 'accepted', '0.0004'], ['0.0006', 'accepted', '0.0006'], ['0.0002', 'countered', '0.0005'], ['0.0001', 'countered', '0.00045'], ['0.01', 'accepted', '0.0008']]

const until = Date.now() + DURATION_S * 1000
const started = Date.now()
await Promise.all(users.map(async (u, n) => {
const engineHeaders = { 'x-engine-key': ENGINE_KEY, 'x-wallet-token': u.walletToken }
let i = n
while (Date.now() < until) {
i++
await timed('quotes', async () => {
const r = await fetch(`${base}/internal/v1/shop/gas-price?quotes=1`, { headers: engineHeaders })
const b = await r.json()
return r.status === 200 && b.quotes.length === 3 && b.quotes[0].seller === 's2'
})
const [offer, status, price] = OFFERS[i % OFFERS.length]
await timed('offer', async () => {
const r = await fetch(`${base}/internal/v1/shop/network-status?seller=s2&offer=${offer}`, { headers: engineHeaders })
const b = await r.json()
return r.status === 200 && b.status === status && b.priceNear === price && b.payTo === 'cheap.testnet'
})
if (i % 3 === 0) await timed('csv', async () => {
const r = await fetch(`${base}/v1/minds/${u.mindId}/payments.csv`, { headers: { cookie: u.cookie } })
const text = await r.text()
const lines = text.trimEnd().split('\r\n')
return r.status === 200 && lines.length === PAYMENTS_PER_MIND + 1 && lines.filter((l) => l.includes(',your rule,')).length === PAYMENTS_PER_MIND / 2
})
}
}))
const seconds = (Date.now() - started) / 1000
const pct = (xs: number[], p: number) => xs.slice().sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor((p / 100) * xs.length))]?.toFixed(1)
for (const [name, xs] of Object.entries(latencies)) {
console.log(`${name}: ${xs.length} requests, ${(xs.length / seconds).toFixed(1)}/s, p50 ${pct(xs, 50)} ms, p95 ${pct(xs, 95)} ms, max ${pct(xs, 100)} ms`)
}
console.log(`VUs: ${VUS}, ${seconds.toFixed(1)} s; errors: ${errors}`)

await query(`delete from users where near_account_id like 'loadshop-%'`)
server.close()
engine.close()
outlayerServer.close()
await pool.end()
process.exit(errors || Object.values(latencies).some((xs) => !xs.length) ? 1 : 0)
4 changes: 3 additions & 1 deletion apps/be/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@
"dev": "node --env-file=.env --import tsx src/server.ts",
"migrate": "node --env-file=.env --import tsx src/migrate.ts",
"test": "node --env-file-if-exists=.env --import tsx --test --test-concurrency=1 test/*.test.ts",
"test:unit": "node --import tsx --test test/crypto.test.ts test/sse.test.ts test/telegram-format.test.ts test/approvals.test.ts",
"test:unit": "node --import tsx --test test/crypto.test.ts test/sse.test.ts test/telegram-format.test.ts test/approvals.test.ts test/relay.test.ts",
"load": "node --env-file-if-exists=.env --import tsx load/api.ts",
"load:shop": "node --env-file-if-exists=.env --import tsx load/shop.ts",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"borsh": "2.0.0",
"near-api-js": "7.4.0",
"pg": "8.23.1",
"zod": "4.6.7"
Expand Down
7 changes: 7 additions & 0 deletions apps/be/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ export const config = {
authRecipient: process.env.AUTH_RECIPIENT ?? 'hellonear.app',
authMessage: 'Sign in to HelloNear',
nearRpcUrl: process.env.NEAR_RPC_URL ?? 'https://rpc.testnet.near.org',
// Meta-transaction relayer (realworld track, src/relay.ts): it pays gas only for allowed calls to the registry contract.
// Off (503 relay_not_configured) until both relayer values are set. rpc.testnet.near.org is deprecated, so the relay
// defaults to FastNear's testnet RPC unless NEAR_RPC_URL names another.
registryContractId: process.env.REGISTRY_CONTRACT_ID ?? 'hellonear-registry.testnet',
relayerAccountId: process.env.RELAYER_ACCOUNT_ID ?? '',
relayerPrivateKey: process.env.RELAYER_PRIVATE_KEY ?? '',
relayRpcUrl: process.env.NEAR_RPC_URL ?? 'https://test.rpc.fastnear.com',
cookieSecure: process.env.COOKIE_SECURE === 'true',
// Judge try-out mode (#43). Off unless DEMO_MODE=true; the shared demo wallet's agent key is optional.
demoMode: process.env.DEMO_MODE === 'true',
Expand Down
50 changes: 50 additions & 0 deletions apps/be/src/payments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,53 @@ export async function listPayments(mindId: string, limit = 20) {
...(p.tx_hash ? { txHash: p.tx_hash } : {}), ...(p.message ? { message: p.message } : {}), at: p.created_at.toISOString(),
}))
}

// CSV of a Mind's payments for an accountant (realworld track): one row per attempt, newest first, in words that need
// no explaining. "Approved by" comes from the run that made the payment: a `tool.called` with `approvedBy: "rule"` is the
// owner's auto-approve rule (#167), a `tool.approval_required` for the same call is the owner's own approval.
const CSV_STATUS: Record<PaymentStatus, string> = {
sent: 'sent', pending: 'pending', policy_denied: 'refused by the wallet policy (no money moved)',
wallet_frozen: 'refused, wallet frozen (no money moved)', failed: 'failed (no money moved)',
}
export const CSV_HEADER = ['Date (UTC)', 'Status', 'Direction', 'Amount (NEAR)', 'Counterparty', 'Purpose', 'Approved by', 'Transaction hash', 'Explorer link', 'Note']
// RFC 4180 quoting, and a leading ' on a cell that a spreadsheet would read as a formula.
export function csvCell(v: string): string {
const safe = /^[=+\-@\t\r]/.test(v) ? `'${v}` : v
return /[",\r\n]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe
}
export async function paymentsCsv(mindId: string, limit = 10_000): Promise<string> {
// One pass: the payment calls in this Mind's runs, then who approved each, then the rows (no per-row subqueries).
const rows = await query<{ id: string; created_at: Date; status: PaymentStatus; amount_yocto: string; to_account: string; tx_hash: string | null; message: string | null; shop_item: string | null; offer_item: string | null; approved_by: string | null }>(
`with calls as (
select e.payload->'result'->>'paymentId' as payment_id, e.run_id, e.payload->>'toolCallId' as call
from run_events e join runs r on r.id = e.run_id
where r.mind_id = $1 and e.type in ('tool.result', 'tool.error') and e.payload->'result' ? 'paymentId'
), approvals as (
select c.payment_id,
bool_or(a.type = 'tool.called' and a.payload->>'approvedBy' = 'rule') as by_rule,
bool_or(a.type = 'tool.approval_required') as by_owner
from calls c join run_events a on a.run_id = c.run_id and a.type in ('tool.called', 'tool.approval_required') and a.payload->>'toolCallId' = c.call
group by c.payment_id
)
select p.id, p.created_at, p.status, p.amount_yocto, p.to_account, p.tx_hash, p.message, s.item as shop_item, o.item as offer_item,
case when ap.by_rule then 'your rule' when ap.by_owner then 'owner' end as approved_by
from wallet_payments p
left join approvals ap on ap.payment_id = p.id
left join (select distinct on (payment_id) payment_id, item from shop_purchases where mind_id = $1) s on s.payment_id = p.id
left join (select distinct on (payment_id) payment_id, item from offer_purchases where buyer_mind_id = $1) o on o.payment_id = p.id
where p.mind_id = $1 order by p.created_at desc limit $2`, [mindId, limit])
const lines = [CSV_HEADER, ...rows.map((p) => [
p.created_at.toISOString().replace('T', ' ').slice(0, 19),
CSV_STATUS[p.status] ?? p.status,
'out',
toNear(BigInt(p.amount_yocto)),
p.to_account,
p.shop_item ? `data report: ${p.shop_item}` : p.offer_item ? `bought from another Mind: ${p.offer_item}` : '',
p.approved_by ?? '',
p.tx_hash ?? '',
p.tx_hash ? `https://testnet.nearblocks.io/txns/${encodeURIComponent(p.tx_hash)}` : '',
p.message ?? '',
])]
// A BOM so Excel opens it as UTF-8; CRLF line ends per RFC 4180.
return '' + lines.map((l) => l.map(csvCell).join(',')).join('\r\n') + '\r\n'
}
Loading
Loading