Run the sandbox on your computer, report one use of AI and get a receipt you can verify.
Before you start
- Node.js 22.12 or later
- pnpm 10
- PostgreSQL 16. By default, the sandbox uses the Homebrew location on macOS. Set the
PG_BINenvironment variable if PostgreSQL is installed elsewhere - Access to the project repository. It is currently private, so ask the project team for access
Run all the commands below from the root of the repository. Windows has not been tested.
Run the sandbox
1. Install dependencies
pnpm install2. Start the database
pnpm db:startThis starts a PostgreSQL instance used only by this project. It listens only on 127.0.0.1:54329. It has no password and is only for local development. It does not affect any other PostgreSQL installation on your computer.
3. Create sample data
pnpm seedThis creates the sample account, source pool and test keys. The keys are saved in .local/, which Git ignores. Do not commit or share this folder.
4. Start the server
pnpm devThe server is ready when you see the line below, which means “Sandbox server started”. Command output is currently in Chinese. Keep this terminal open:
沙盒服务已启动:http://127.0.0.1:43105. Get your first receipt
Open another terminal and run:
pnpm demoThe demo reports the same request through both the SDK and a gateway. The sandbox combines the two reports, then matches and verifies the usage. The steps in the output are: the SDK report, the gateway’s duplicate report (added to the same usage), the quote, the reservation (a retry returns the same one), settlement and verification. The last line is the receipt’s address. The output looks like this:
1. SDK 上报: created { value: '682000', unit: 'uWh' }
2. 网关重复上报,归入同一用量: true
3. 报价: { value: '682000', unit: 'uWh' } { currency: 'USD_TEST', value: '0.00000341' }
4. 预留: reserved ;重试返回同一笔: true
5. 结算: confirmed { value: '682000', unit: 'uWh' }
6. 核验: signature=pass,batch_manifest=pass,latest_version=pass,…
收据页面:http://127.0.0.1:4310/r/rct_…Open the address on the last line in your browser to see the receipt.
6. Open the console
Open http://127.0.0.1:4310/console/ and sign in with the key in .local/admin-key. On macOS, you can copy the key with this command:
pbcopy < .local/admin-keySee the User Guide for how to use each page. The console is currently in Chinese.
Complete a match with the SDK
The SDK is not on npm yet, so you can currently use it only inside the repository.
First, make sure you have an active grant. pnpm demo creates a grant for the agent key that lasts one hour. If it has expired, run the demo again. You can also create a new grant for the agent key under Budget grants (预算授权) in the console.
Create a file named scripts/my-first-match.ts:
import { randomUUID } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { ArecClient } from '@arec-ai/sdk';
const c = JSON.parse(await readFile('.local/demo-credentials.json', 'utf8'));
const arec = new ArecClient({ baseUrl: 'http://127.0.0.1:4310', apiKey: c.agentToken });
const scope = { project_id: c.projectId, beneficiary_scope_id: c.scopeId };
// 1. Report usage. Only example/model-demo has test coefficients
const requestId = randomUUID();
const event = await arec.reportUsage({
...scope,
source_id: 'my-app',
external_event_id: requestId,
provider_request_id: requestId,
revision: 1,
event_type: 'usage_snapshot',
occurred_at: new Date().toISOString(),
evidence_level: 'runtime_reported',
model: { provider: 'example', id: 'model-demo' },
usage_semantics: 'openai_responses_v1',
usage: { input_tokens: 1000, output_tokens: 600 },
});
// 2. Find a grant, then get a quote. A quote does not spend anything
const grant = (await arec.listGrants()).find((g) =>
g.project_id === scope.project_id && g.beneficiary_scope_id === scope.beneficiary_scope_id);
if (!grant) throw new Error('No active grant. Create one first');
const quote = await arec.createQuote({
...scope,
source_pool_id: grant.source_pool_id,
usage_event_ids: [event.usage_event_id],
});
console.log('Quote:', quote.target_energy, quote.charge);
// 3. Accept the quote, wait for settlement, then verify the receipt
const accepted = await arec.match({
quote_id: quote.quote_id,
usage_event_ids: quote.usage_event_ids,
budget_grant_id: grant.budget_grant_id,
max_charge: quote.charge,
});
const match = await arec.waitForMatch(accepted.match_id);
const verification = await arec.verifyReceipt(accepted.receipt_id);
console.log('Status:', match.status, '; failed checks:', verification.has_failed_check);
console.log(`Receipt: http://127.0.0.1:4310/r/${accepted.receipt_id}`);pnpm exec tsx scripts/my-first-match.tsYou should see 700000 uWh (0.7 Wh), a status of confirmed and no failed checks.
When reporting usage, we recommend the SDK’s local queue, UsageOutbox. If you go offline, it saves usage on your computer and sends it once you are back online. Usage from real models can be recorded, but it cannot be estimated or matched yet because there are no reliable coefficients.
Connect an agent
Through MCP, an agent can use an existing budget grant to get quotes, make matches and look up receipts. MCP does not collect usage automatically. It also cannot create a grant or raise its limits.
arec_get_statusCheck grants and unmatched usagearec_quoteGet a quote without spendingarec_matchMake a match within the grant; this spends moneyarec_get_receiptWait until complete, then verify
Build the MCP server first. You can skip this step if you have already run pnpm dev:
pnpm buildThen add this configuration to your MCP client, using the actual absolute paths:
{
"mcpServers": {
"arec": {
"command": "node",
"args": ["/absolute/path/AREC-V2/packages/mcp/dist/main.js"],
"env": {
"AREC_API_URL": "http://127.0.0.1:4310",
"AREC_API_KEY_FILE": "/absolute/path/AREC-V2/.local/agent-key"
}
}
}
}You can also run the full agent demo. The SDK reports usage, and MCP handles the other steps.
pnpm demo:agentVerify a receipt offline
Download the receipt package. Replace <receipt-id> with the ID that starts with rct_:
curl -s http://127.0.0.1:4310/v1/public/receipts/<receipt-id>/package -o receipt-package.jsonSave the sandbox’s public signing key:
curl -s http://127.0.0.1:4310/v1/keys | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>process.stdout.write(JSON.parse(s).keys[0].public_key_pem))' > trusted-key.pemVerify the receipt:
pnpm verify receipt-package.json trusted-key.pemOffline verification checks only the signature, batch manifest and amounts. It does not check the on-chain record or whether this is the latest version. Here, the public key comes from the same server only for this demo. In real use, it must come from a separate trusted source.
Stop the sandbox
Press Ctrl+C in the terminal running the server, then stop the database. Your data will be kept:
pnpm db:stopTroubleshooting
| Problem | What to do |
|---|---|
| PostgreSQL cannot be found | Set PG_BIN to the bin folder of PostgreSQL 16 |
| Port 4310 is already in use | Use another port, such as PORT=4311 pnpm dev, and change the addresses in this guide to match. When you run pnpm demo again, add PORT=4311 there too |
| There is no active grant | Run pnpm demo again, or create a grant in the console |
| Usage shows “Cannot be estimated” (无法估算) | There are no reliable coefficients for real models yet. Use example/model-demo for the demo |
A match stays reserved | It may be below the smallest unit or minimum retirement amount, or there may not be enough supply. Any remainder is kept for the next batch |
Next, read the User Guide to learn everyday tasks, or see the Tech Docs for the API and rules.