This document covers the sandbox’s current architecture, API and rules for v0.1. For features that have not been built, see the last section. For Arkreen’s existing certificate protocol, see AREC Protocol.
System architecture
There are six main steps:
- Receive usage, remove duplicates and estimate electricity.
- Create a quote for the electricity waiting to be matched.
- Check the budget and reserve funds and supply in one database transaction.
- Group allocations into batches by tenant, payer, beneficiary scope and source pool. Save each transaction before broadcasting it.
- Once there are enough confirmations, record the actual net amount on-chain.
- Issue a new version of each affected match’s receipt.
| Ledger | What it records | Constraints |
|---|---|---|
| Usage ledger | Events, metering units and estimates | Events and estimates can only be added. The same underlying usage is recorded only once |
| Entitlement ledger | Supply, allocations and settlement batches | A batch’s active allocations cannot exceed its net retirement |
| Funds ledger | Balances and held funds | The balance cannot be lower than the held amount |
Every change to funds or supply is written to an append-only log, so current balances can be recalculated from it. Electricity and money are recorded separately and cannot stand in for each other.
| Code | Contents |
|---|---|
src/modules/usage.ts, normalize.ts, estimate.ts | Usage, normalization and estimates |
src/modules/matching.ts | Quotes, grants, idempotency and reservations |
src/modules/plans.ts, sponsorships.ts, payments.ts | Automatic plans, sponsorships and x402 top-ups |
src/modules/settlement.ts | Batching, reconciliation, recovery and batch problems |
src/modules/evidence.ts, wallets.ts | Reporter signatures, total checks, data connections, legacy records and wallet links |
src/modules/reports.ts, statements.ts | Reports, monthly certificates and sharing |
src/modules/accounts.ts, operations.ts, support.ts | Members and keys, platform operations and support tickets |
src/modules/webhooks.ts | Notifications, signatures, retries and URL checks |
src/api-reference.ts, src/openapi.ts | Endpoint list, OpenAPI and llms.txt |
src/modules/receipts.ts, src/verify-package.ts | Receipt issuance and verification |
src/chain/types.ts | Chain adapter interface |
src/chain/evm.ts | Real-chain adapter, not connected to the running service |
migrations/ | Database tables, constraints and append-only rules |
Units and precision
All quantities are stored and calculated as integers. Floating-point numbers are not used.
| Unit | Used for | Conversion |
|---|---|---|
μWh (uWh in the API) | Usage, allocations and matches | 1 kWh = 1,000,000,000 μWh |
| mWh (milliwatt-hour) | On-chain settlement | 1 mWh = 1,000 μWh, which is also the smallest unit of ART |
| ART | On-chain token | 1 ART = 1,000 kWh |
| pUSD | Internal amounts of money | 1 USD_TEST = 1,000,000,000,000 pUSD |
The API always returns electricity in uWh, with the value as a string. Direct electricity data can be reported in uWh, mWh, Wh or kWh. Values more precise than 1 μWh are rejected, not rounded.
Prices are whole numbers of pUSD/μWh. The smallest possible price is 1 USD_TEST/MWh (megawatt-hour). The sandbox price is 5 pUSD/μWh, or 5 USD_TEST/MWh, and is fictional.
Report usage
This is a usage report with a request ID:
{
"project_id": "prj_demo",
"beneficiary_scope_id": "scope_demo",
"source_id": "my-app",
"external_event_id": "request-001",
"provider_request_id": "request-001",
"revision": 1,
"event_type": "usage_snapshot",
"accounting_role": "metering",
"occurred_at": "2026-11-29T08:30:00Z",
"evidence_level": "runtime_reported",
"model": { "provider": "example", "id": "model-demo" },
"usage_semantics": "openai_responses_v1",
"usage": { "input_tokens": 1000, "output_tokens": 600 }
}Provide at least one of usage and energy. If you provide usage, you must also provide usage_semantics. If you provide provider_request_id, you must also provide model.
The server stores only normalized token counts, not the provider’s raw usage data. Fields used as identifiers cannot contain control characters. Use tags to add up to 10 tags, such as a team or app, for grouping reports. Tag names can contain only lowercase letters, numbers and underscores. Values can have up to 100 characters. Do not put prompts, answers or personal information in IDs, tags or similar fields.
Deduplication
When there is a provider_request_id, the system deduplicates by tenant, provider and request ID, and event_type must be usage_snapshot. Without one, it identifies events by project, source and event ID. usage_delta represents a separate increment of usage.
If several sources report the same request, the metering source is chosen in this order:
- A source whose reporter signature has been verified.
- The higher evidence level. From highest to lowest:
metered,provider_reported,runtime_reported,self_reported. - At the same level, a source with direct electricity data.
- If they are still equal, the source that reported first.
If the electricity estimates differ, the metering unit is marked to show this. Reporters declare their own evidence level, and the system does not verify it. A signature can only prove who provided the data and that it has not changed, not that the values are accurate.
A request can belong to only one project and beneficiary scope. Otherwise, scope_conflict is returned. The system does not deduplicate across tenants.
Revisions
- Same revision, same contents: returns
duplicatewithout recording it again. - Same revision, different contents: returns
event_conflict. - Higher revision: replaces that source’s earlier data. An older revision cannot overwrite it, even if it arrives later.
- A revision cannot change the request ID, provider or metering method. Otherwise,
identity_changedis returned.
If electricity increases after a match, only the difference can be quoted again. If it decreases, existing allocations stay in place. Use accounting_role: "rollup" for a parent task’s total. Rollups are only recorded and are not included in metering, so usage is not counted twice.
Reporter signatures
Meters, gateways and providers can sign usage with Ed25519. First register the public key and link it to a source_id, then use attestUsage from the SDK. The server accepts only public keys. The private key must stay with the reporter.
The signed content is the prefix arec-usage/v1\n followed by the original request without attestation. The request is encoded as deterministic JSON with sorted keys, and its numbers must be integers. An invalid signature, the wrong source or a disabled public key returns invalid_attestation. The data is not accepted as unverified instead. Disabling a public key does not affect data already received.
Normalize tokens
usage_semantics | How it is handled |
|---|---|
normalized_disjoint_v1 | Uses token categories that do not overlap, with no changes |
openai_responses_v1 | Cached tokens are part of the input, and reasoning tokens are part of the output, so they are separated first. Only the Responses API is supported |
anthropic_messages_v1 | input_tokens does not include cache reads or writes. Thinking tokens are already included in output_tokens |
When an Anthropic response includes usage.iterations, it may cover several runs, such as compaction or a change of model. The top-level usage alone is not enough:
- The server adds up all the runs and does not add the top-level numbers again. If there is only one run and it matches the top level, the top-level numbers are used to keep the thinking details.
- If more than one model was used, the SDK splits usage by model. Any part with no model listed, and no way to infer it, is recorded as
unknown. - The server rejects data that has not been split and returns
mixed_models.
Estimate electricity
Estimates follow these steps:
- If
energyis provided, it is used directly. No token estimate is added, and it is not multiplied by PUE again. - Otherwise, the system looks for an estimation method that has taken effect. A method for the specific model version comes first, followed by the version that took effect most recently.
- If there is no method for this usage, a fallback method is used only if the project allows it. Its basis is marked
fallback. - If no method applies, electricity is
nulland the basis isunsupported. It is never counted as zero.
There are two types of estimation method:
| Type | How it is calculated |
|---|---|
token_coefficients | Multiplies each non-overlapping token category by its coefficient, then adds a fixed overhead |
per_task | Uses the total for the whole task directly, without adding tokens |
Each version must explain its data source, energy boundary, applicable workloads, input definitions and uncertainty. Published versions cannot be changed, and a new version applies only to later estimates. POST /v1/projects/:id/reestimate handles only usage that could not be estimated before. It does not change existing estimates or receipts.
The sandbox has test coefficients only for example/model-demo:
| Token category | Fictional coefficient (μWh / token) |
|---|---|
| Uncached input | 100 |
| Cached input | 10 |
| Cache write | 125 |
| Visible output | 1,000 |
| Reasoning output | 1,000 |
For example, 1,000 uncached input tokens and 600 output tokens come to 100,000 + 600,000 = 700,000 μWh.
Coverage is confirmed electricity divided by recorded electricity. Each metering unit counts for no more than 100%. match_ratio_bps is in basis points and is always rounded down:
status | Meaning | match_ratio_bps |
|---|---|---|
known | All recorded usage can be estimated | 0 to 10,000 |
unknown | At least one usage item cannot be estimated | null |
no_usage | There is no electricity to count | null |
Coverage applies only to recorded usage. Purchase buffers do not count towards it. Where external registration is required, electricity counts only after registration is confirmed.
Compare with provider totals
A tenant can submit a provider’s token totals for a period and compare each category with recorded usage. The comparison is redone each time it is viewed, so data that arrives late is included.
source_completeness | Meaning |
|---|---|
not_verified | There is no total for exactly the same period, or at least one provider’s total is missing |
provider_totals_match | Totals were provided for every recorded provider in this period, and all of them match |
provider_totals_mismatch | At least one total does not match |
The system does not verify bills. Matching totals do not prove that collection is complete, because providers and tools that are not connected are not compared. Queries by beneficiary scope always return not_verified.
Data connections and legacy records
Once you set a data connection’s normal reporting interval, its status becomes stale if no data arrives for too long. ok means only that data arrived recently, not that collection is complete.
Legacy Photosynth records can be imported as legacy_sample, but are not included in metering, matching or coverage. If a record has a wallet address, the wallet must first be linked with a signature. The text to sign is valid for 10 minutes. It can be used only once and cannot be used for another account. Linking a wallet does not send a transaction. Only standard wallets (EOAs) are currently supported.
The legacy endpoint /legacy/photosynth/offset returns only upgrade_required. It does not read or save any data. It never returns accepted, because the old plugin would take that to mean the offset had been accepted.
Quotes and budgets
A quote locks the metering units, estimate versions, electricity, source pool and price. It is valid for 10 minutes and can be used only once. It can include up to 500 usage events. A quote does not reserve supply. If usage or allocations have changed by the time it is accepted, quote_stale is returned.
| Quote option | Default | Meaning |
|---|---|---|
target_ratio_bps | 10000 | Target coverage. 10000 means 100%. The rest can be matched later |
buffer_bps | 0 | Extra amount to buy above the target. The grant must allow it |
settlement_mode | batch | independent creates a separate batch |
A purchase buffer is shown separately on the receipt. It does not count towards the electricity target or coverage, and cannot make up for missed usage. Settlement fills the electricity target before the buffer. A grant’s max_buffer_bps is 0 by default, so buffers are not allowed unless this is changed.
charge is the total price. charge_breakdown lists energy attribute purchases, execution costs and software service fees separately. The last two are charged per match and are both 0 by default in the sandbox. These fees are held when a match is accepted and charged only after some electricity is confirmed. They are released if everything fails, and the charge is reversed after a chain reorganization. Fees also count towards budget limits.
Source pools have two modes:
mode | Rule |
|---|---|
support | Renewable energy support, with no matching rule |
attribute | Matches energy attributes to electricity use under the same_year rule. The year of use must be the same as the generation year of every source in the pool (UTC) |
The source cannot be chosen at retirement, so every source in the pool must meet the rule. This is checked again when supply is reserved, and settlement also checks the sources actually used. The sample data has only a support source pool. These rules are also fictional and do not show compliance with any market rules.
A match must use every ID in the quote’s usage_event_ids and include max_charge. The server checks that:
- The grant belongs to the current key and has not been revoked or expired
- The project, beneficiary scope and source pool match the quote
- The limits per match, per day and per month are not exceeded
- The purchase buffer is within the percentage allowed by the grant
- The payer has enough funds and the source pool has enough supply. If a sponsorship is used, its limit must not be exceeded either
- The quote is still valid and does not cost more than
max_charge
Daily and monthly limits use UTC. Reserved, submitted and confirmed amounts all count towards the limits, but released amounts do not. The checks and reservation happen in one database transaction. Row locks prevent concurrent requests from overspending or overselling.
Sponsorships
When a sponsor creates a sponsorship, they receive a claim code that is shown only once. The recipient links it to a beneficiary scope when claiming it. The sponsor pays only if the recipient then chooses this sponsorship for a new grant or plan.
- The sponsorship amount is a spending limit. Funds are not held in advance. Every match checks the remaining amount and the sponsor’s balance.
- If the sponsor’s balance is too low, the match fails. It will not use the recipient’s money instead.
- If different accounts pay for the same beneficiary scope, their matches go into different batches. Charges, and any reversals after a chain reorganization, are recorded in the account that actually paid.
- Sponsors see only totals, not the recipient’s account, usage or receipts. Recipients can see the sponsor’s name and the remaining amount.
- Revoking a sponsorship prevents new spending, but matches that have already been accepted will still be settled.
Idempotency and retries
Every match must include an Idempotency-Key with 8 to 200 characters.
- Same key, request and idempotency key: returns the result from when the match was first accepted. This is a snapshot from that time, so check the latest status separately.
- Same idempotency key, but a different request or API key: returns
idempotency_conflict. - The request was not accepted: the idempotency key is not used up. After fixing the problem, you can retry with the same key.
- The response is lost, followed by a 401, 403 or 429: this does not mean the earlier request failed. Fix the problem first, then retry with exactly the same arguments and idempotency key.
Automatic matching plans
A plan automatically matches new usage within its budget, without asking you to confirm each match. Each beneficiary scope can have only one plan that has not been cancelled.
Each plan has its own budget grant and uses the same limit checks and row locks as manual matches. No key can use this grant, and it cannot be revoked separately. It can be disabled only by cancelling the plan.
{
"project_id": "prj_demo",
"beneficiary_scope_id": "scope_demo",
"source_pool_id": "pool_sandbox",
"include_existing": false,
"interval_minutes": 60,
"per_match_limit": { "currency": "USD_TEST", "value": "0.01" },
"daily_limit": { "currency": "USD_TEST", "value": "0.1" },
"monthly_limit": { "currency": "USD_TEST", "value": "0.5" },
"max_price_per_kwh": { "currency": "USD_TEST", "value": "0.005" },
"expires_at": "2026-12-29T00:00:00Z"
}You can also set target_ratio_bps, buffer_bps, settlement_mode, on_limit and sponsorship_id. The first three work the same way as the quote options. When you edit a plan, any options you leave out stay the same. sponsorship_id cannot be changed after the plan is created.
The interval can be 1 to 1,440 minutes, and a plan can last up to 366 days. The maximum unit price is converted to a whole number of pUSD/μWh and rounded down.
What gets matched
- Time range: By default, only usage after the plan was created is matched. Both the time of use and the time the server first received it must be no earlier than the plan’s creation. Reporters provide the time of use. If only that time were checked, a fast clock could cause earlier usage to be charged. When
include_existingistrue, earlier unmatched usage is also included. - Stable estimates: The current estimate must stay the same for at least 5 minutes before it is matched. Changing the metering source restarts this wait. This reduces, but cannot fully prevent, buying too much if usage is revised down.
- Usage that can be estimated: Usage with no applicable estimation method is skipped.
- Source rules: If the year of use does not meet the source pool’s rule, the usage is skipped and a reason is given.
Older usage is handled first, with up to 500 items at a time. A large item that does not fit is skipped for now, so it does not block smaller items after it. A single item is never split. If it costs more than the limit per match, raise the limit or match it manually.
Run results
last_outcome | Meaning |
|---|---|
matched | All eligible usage was accepted. This does not mean settlement is complete |
partial | Only some usage was accepted. See last_reason |
idle | There was no eligible usage. This includes usage whose estimate is not stable yet |
blocked | A restriction prevented any matches. See last_reason |
error | An error occurred. Everything was rolled back, and the plan will try again after 1 minute |
last_reason can be per_match_limit, daily_limit, monthly_limit, insufficient_funds, insufficient_inventory, price_too_high, sponsorship_limit, sponsorship_unavailable, source_not_applicable, grant_expired, more_pending or internal_error. more_pending means the item limit for one run was reached. The background worker will continue as soon as possible. If the budget, balance or supply is the limit, the plan waits until its next interval.
If more than one limit applies, only the one with the least remaining at that time is returned. After you resolve it, another limit may still apply.
Strict mode
By default, plans do not affect AI tasks (on_limit is continue). For stricter control, set it to block and check GET /v1/coverage-decision before each new task. It returns decision: "block" and a reason if the plan is paused, has expired, is more than 5 minutes late to run or cannot match normally.
The service only gives a recommendation. It does not block tasks. The integration decides what to do if the check fails. continue also means only that the plan has been running normally, not that the new task has been matched.
Edit or stop a plan
- Edit: This updates the existing grant, so the amounts already used today and this month are not reset. The plan runs as soon as possible after it is saved. A paused plan stays paused.
- Pause or cancel: If the plan is running, that run finishes first. Once the request succeeds, there will be no new matches. Matches that have already been accepted continue.
- Resume: The plan runs as soon as possible and also matches usage from while it was paused.
- Cancel: This cannot be undone. You can create a new plan, but its limits start again and do not include the old plan’s spending.
- Run soon:
runonly asks the background worker to run the plan. It does not wait for matching to finish.
Plans and manual matches can be used together. The same unmatched electricity will not be reserved twice. Their limits are separate, so total spending can be as high as all the grants combined.
Settlement and recovery
Match statuses
The status combines all allocations and their batches. If any batch needs reconciliation, the match is reconciliation_required. Otherwise, if any allocation is still being settled, it is submitted.
Batch statuses
Allocations are grouped into batches by tenant, payer, beneficiary scope and source pool. Matches set to independent get their own batch. By default, settlement happens as soon as possible. A project can also have a maximum wait and an optional amount; settlement starts when either is reached. This setting does not affect separate settlement or period close. Every stage is saved to the database first, and a database lock allows only one settlement job to run at a time.
- Create a batch: Only full units of 1 mWh are settled. Any remainder waits for the next batch. The batch must also reach the minimum net retirement amount on-chain.
- Save, then broadcast: The nonce, raw transaction and hash are saved before broadcasting. If the result is unclear, the system only looks up or rebroadcasts the same transaction.
- Enough confirmations: Amounts are posted after 2 confirmations. After 12, they are considered final and are no longer checked for reorganizations.
- Reorganization: Before 12 confirmations, if the transaction disappears or its block changes, the posting is reversed and the funds are put back on hold. The system then keeps checking the original transaction.
- Reverted transaction: A retry happens only after 12 confirmations. If the same allocation is reverted 3 times in a row, its funds and supply are released. Retrying too soon could retire it twice after a reorganization.
- Source mismatch: The actual amount is deducted from supply. Completion claims and automatic processing stop, and a platform operator handles the batch. Until then, the related funds and reservations are kept.
To handle a source mismatch, an operator can release the reservation. They can also queue it again, which retires another batch. The original batch becomes closed. The amount already retired stays on record as retired but unallocated, and cannot be sold again. Batches that are still being checked automatically cannot be handled manually, because they could be retired twice.
External registries
Some source pools also require registration in an external registry. The registration status is kept separately from the on-chain status: not_applicable, pending, confirmed or failed. An operator can enter the registration result only after the batch is final. A failed registration can later be changed to confirmed. Once confirmed, it cannot be changed.
If a match is confirmed on-chain but its registration is not, its status may be confirmed while its claim_status is still pending. To check whether it is complete, make sure claim_status is sandbox_complete.
Fees and net amounts
fee = floor(gross × fee rate)
net = gross - feeWhen creating a batch, the gross amount is calculated as follows:
gross = floor(target net × 10,000 ÷ (10,000 - fee rate))The fee rate in this formula is in basis points. When the existing ART contract uses only one source, it calculates the fee again after taking the net amount. The actual charge can therefore be higher than the gross amount submitted. For example, with a 1% fee rate and a net amount of 198, submitting 199 results in a charge of 200. With this formula, the charge equals the submitted gross amount whether one or several sources are used. If the fee rate changes after submission, the actual on-chain charge is still recorded.
Only the actual net amount on-chain is posted:
- If the net amount is too low, the difference goes back to being reserved and waits for the next batch.
- At period close, a remainder of less than 1 mWh can be rounded up. The added amount is reserved first. After confirmation, it is recorded separately as an unallocated remainder.
Receipts and verification
Each receipt has append-only versions. A new version is issued when its contents change. Receipts use Ed25519 to sign the fixed prefix arec-receipt/v1\n together with the original receipt. This prevents the signature from being used for another type of content.
Public receipts do not include the tenant, project, beneficiary scope, amounts of money or exact times. The payer and beneficiary scope are shown as salted SHA-256 hashes. Only the tenant that owns the receipt can get the salt and check them. Private receipts also list the payer, beneficiary, user, executor and sponsor.
A receipt shows whether a sponsor paid, how many usage items have a verified reporter signature and the external registration status. If the target is less than the estimated electricity, it says that not all of this usage was matched.
The public verification endpoint POST /v1/verify accepts a receipt ID or a receipt package:
{ "receipt_id": "rct_..." }| Check | What it checks | Offline |
|---|---|---|
signature | The contents match the signature and key ID | Yes |
batch_manifest | The manifest hash, allocations, duplicates and totals are correct | Yes |
latest_version | Whether this is the latest version | No |
retirement_on_chain | The retirement ID, net amount and sources match the on-chain record | No |
allocation_unique | The allocation and batch totals match the platform ledger | No |
matching_rule | same_year source pools check the years of use and generation; support returns not_applicable | No |
If the signature is invalid, the rest of the receipt is neither checked nor trusted. If there is no confirmed settlement, some checks return not_applicable. No failed checks does not mean the match is complete. You must also make sure claim_status is sandbox_complete.
The public key used for offline verification must come from a trusted source outside the receipt package. Verification cannot prove that the electricity estimate is accurate. Whether an allocation is unique still depends on the platform ledger.
Reports and monthly certificates
GET /v1/reports uses UTC months. Data can be grouped by model, task, beneficiary scope, source or tag. Three types of data use different times:
| Data | Time used |
|---|---|
| Usage and coverage | Time of use |
| Spending | When it was posted to the ledger, including reversals after a chain reorganization |
| Matches and purchase buffers | When the match was created |
Spending is split between your own payments and those made by sponsors, with the three types of cost shown separately. Held funds do not count as spending. Viewing amounts of money also requires billing:read. Reports can be exported as CSV, with protection against spreadsheet apps running content as formulas.
Monthly certificates can be issued only after the month ends. They can cover the whole project or one beneficiary scope. If late data arrives, issuing a certificate again creates a new version and leaves earlier versions unchanged. If nothing has changed, it is not issued again. Certificates are signed with a different fixed prefix, arec-statement/v1\n, so their signatures cannot be used for receipts or the other way around.
Monthly certificates are private by default. Users can choose to share a monthly certificate or their total support, set an expiry date and revoke the share at any time. Public content does not include accounts, projects, beneficiary scopes, amounts of money or receipt lists. The receipt list appears only as a hash. Revoking a share cannot take back anything others have already saved.
Webhooks
Notifications are saved in the same database transaction as the changes that cause them, then sent by a background worker. Each one is sent at least once. It may be sent more than once or arrive out of order, so use the notification ID to remove duplicates.
| Type | When it is sent |
|---|---|
receipt.updated | A receipt has a new version, including when a match is first accepted |
plan.attention | A plan has a problem, its reason changes or it expires |
plan.recovered | A plan is working normally again |
statement.issued | A new version of a monthly certificate is issued |
webhook.test | A test notification is sent manually. You do not need to subscribe to it |
Requests include these headers:
arec-webhook-id: evt_...
arec-webhook-timestamp: 1795939200
arec-webhook-signature: v1=<hex signature>The signature uses HMAC-SHA256 over <notification ID>.<timestamp>.<raw body>. Use the full text of the secret, including whsec_ at the start. For 24 hours after the secret is rotated, the signature header has two signatures separated by a space. Both TypeScript and Python have functions to check them. Always check the raw body. Do not parse and serialize it again first.
- A delivery succeeds only if it gets a 2xx response within 10 seconds. Redirects are not followed, and the response body is not saved.
- After each failure, the wait is 10 seconds, 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and then 12 hours. If every attempt fails, delivery stops. You can replay it manually with the same notification ID.
- URLs must use HTTPS on the public internet. Each delivery checks every address the domain resolves to and connects only to a checked address. This prevents access to private networks.
- For local debugging, set
WEBHOOK_ALLOW_LOCAL=true. This allows only local addresses. Do not use it in production.
x402 top-ups
The sandbox uses the exact scheme from x402 v2 (EIP-3009) to top up test currency. The key needs the payment:write permission:
- Create an order with
POST /v1/payment-orders. It is valid for 15 minutes. - Call
POST /v1/payment-orders/:id/payand get the payment requirements fromPAYMENT-REQUIREDin the 402 response. - Sign with a test wallet, put the payment proof in
PAYMENT-SIGNATUREand send the request again. - A 200 response means the top-up has been posted. The result is in
PAYMENT-RESPONSE.
The chain ID and token address are fictional. The signature is tied to them and cannot be used with real tokens. Even so, do not use a real wallet’s private key.
The service saves the payment proof before requesting settlement. A 202 response means the result is still unclear, so retry only with the same payment proof. The background worker also keeps processing it. Once the charge is confirmed, the top-up is posted even if the order has expired. Each authorization can be used for only one order. An operator can refund an unused top-up. A real payment would also need to be refunded separately through the payment provider.
Embedded components
<script src="http://127.0.0.1:4310/embed/v1.js" defer></script>
<arec-badge receipt="rct_..."></arec-badge>
<arec-receipt receipt="rct_..."></arec-receipt>
<arec-monthly-card share="shr_..." lang="en"></arec-monthly-card>| Component | What it shows |
|---|---|
arec-badge | A receipt status badge that opens the receipt details when clicked |
arec-receipt | A receipt card |
arec-monthly-card | A monthly certificate or total support. You must create a share first |
Components read only public data and do not send cookies. Do not put an API key on the page. A receipt is shown as complete only if no checks have failed and its claim_status is sandbox_complete. Receipts that are not complete refresh regularly. Content is not parsed as HTML, so components also work on pages that restrict inline styles. The page’s CSP must allow scripts to be loaded, and data to be read, from the service’s address.
Authentication and permissions
Server-side programs use Bearer keys. The database stores only a SHA-256 hash of each key:
Authorization: Bearer <api-key>The console exchanges a key for an 8-hour session. Its cookie uses HttpOnly and SameSite=Strict, and the database stores only the token’s hash. Signing in, signing out and writing data through a session also check the Origin, Host and X-Arec-Console request headers.
- A session has the same permissions as the key used to sign in. Revoking the key ends the session immediately.
- If a request includes
Authorization, its cookie is not used, even if the key is invalid. - When using HTTPS, you must set
SECURE_COOKIE=true. This addsSecureand the__Host-prefix to the cookie. - Projects, matches and private receipts that belong to another tenant are treated as “not found”.
Organization accounts can add members. Personal accounts have only one owner. A member key’s permissions come from its role. Permissions for app and agent keys are chosen separately, and these keys can also have an expiry date.
| Role | Permissions |
|---|---|
owner | Full access to the account, including managing members and keys |
admin | Everything except managing members and keys |
finance | View reports and manage budgets, billing and top-ups |
developer | View reports and manage usage, projects and webhooks |
viewer | View reports and receipts only |
- You cannot grant permissions you do not have, or rotate the key of a member with more permissions than you.
- Changing a role, disabling a member or revoking a key takes effect immediately. The system always keeps at least one key that can manage members and does not expire.
- The key itself is returned only once, when it is created. Changes to accounts, budgets, plans and settings are written to an append-only audit log, which never includes the keys themselves.
ops:readandops:writework only for platform accounts. Keys from other accounts cannot use operations endpoints, even if they list these permissions.
Public and sign-in endpoints are rate-limited by IP address: 60 requests per minute for public receipts and verification, 10 for signing in and 20 for claiming sponsorships. Real IP addresses behind a reverse proxy are not supported yet. A proxy must also pass Host through unchanged.
API reference
The local address is http://127.0.0.1:4310. Requests and responses usually use JSON. Web pages, CSV files, the embed script and llms.txt are exceptions. The machine-readable API reference is at /openapi.json, and instructions for agents are at /llms.txt. A request body can be up to 2 MiB. Endpoints with “–” in the permission column do not require a specific permission, but GET /v1/session still requires authentication.
Usage and estimates
| Endpoint | Permission | Purpose |
|---|---|---|
POST/v1/usage-events | usage:write | Report one usage event |
POST/v1/usage-events/batch | usage:write | Report up to 100 events; returns a result for each one |
POST/v1/estimates | estimate:read | Estimate electricity without recording usage |
GET/v1/methodologies | read | List available estimation methods |
GET/v1/pending-usage | quote:read | List unmatched usage |
GET/v1/coverage | report:read | View coverage of recorded usage |
Evidence, checks and data connections
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/reporter-keys | project:admin | List reporter public keys |
POST/v1/reporter-keys | project:admin | Register a reporter’s Ed25519 public key |
POST/v1/reporter-keys/:id/revoke | project:admin | Disable a public key; data already received is not affected |
GET/v1/usage-totals | report:read | View provider totals and compare them with current usage |
POST/v1/usage-totals | project:admin | Submit provider totals to check against usage |
GET/v1/connections | report:read | Check whether data connections are receiving data on time |
POST/v1/connections | project:admin | Add a data connection |
POST/v1/connections/:id/remove | project:admin | Remove a connection; existing data is not affected |
GET/v1/legacy-records | report:read | List legacy Photosynth records |
POST/legacy/photosynth/register | – | Legacy Photosynth registration; no longer in use |
POST/legacy/photosynth/offset | – | Legacy reporting; saves no data and only asks for an upgrade |
GET/legacy/photosynth/status | – | Legacy status; always returns no records |
POST/v1/legacy-records | project:admin | Import legacy records; not included in metering or matching |
Quotes, budgets and matches
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/source-pools | read | View source pools, prices and available supply |
POST/v1/quotes | quote:read | Get a quote without reserving supply |
POST/v1/matches | match:write | Use a grant to accept a quote; requires Idempotency-Key |
GET/v1/matches/:id | read | View a match |
GET/v1/budget-grants | read | List active grants for the current key |
POST/v1/budget-grants | budget:admin | Create a grant |
POST/v1/budget-grants/:id/revoke | budget:admin | Revoke a grant; safe to call more than once |
GET/v1/balances | billing:read | View the status of funds and electricity |
GET/v1/payment-orders | billing:read | View payment orders |
POST/v1/payment-orders | payment:write | Create a top-up order; pay within 15 minutes |
GET/v1/payment-orders/:id | payment:write | View payment orders |
POST/v1/payment-orders/:id/pay | payment:write | Pay with x402 v2 (sandbox) |
GET/v1/sponsorships | billing:read | View sponsorships you offered or claimed |
POST/v1/sponsorships | budget:admin | Create a sponsorship; the claim code is returned only once |
POST/v1/sponsorships/redeem | budget:admin | Claim a sponsorship and link it to a beneficiary scope |
POST/v1/sponsorships/:id/revoke | budget:admin | Revoke a sponsorship you offered |
Automatic matching plans
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/coverage-plans | report:read | View plans, budgets and run results |
POST/v1/coverage-plans | budget:admin | Create a plan; it will then spend automatically |
PATCH/v1/coverage-plans/:id | budget:admin | Edit settings; amounts already used are not reset |
POST/v1/coverage-plans/:id/actions | budget:admin | Pause, resume, run soon or cancel |
GET/v1/coverage-decision | read | Check whether a new AI task is recommended to continue |
Receipts and verification
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/receipts/:id | receipt:read | View a receipt owned by your tenant |
GET/v1/public/receipts/:id/package | – | Download a public receipt package |
GET/v1/public/receipts/:id/summary | – | View a public receipt summary for embedded components |
GET/v1/keys | – | View public signing keys |
POST/v1/verify | – | Verify a receipt ID or package |
GET/r/:id | – | Open a public receipt page |
Reports, monthly certificates and sharing
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/reports | report:read | View or export a monthly report; amounts of money also require billing:read |
GET/v1/statements | report:read | List monthly certificates |
POST/v1/statements | report:read | Issue or update a certificate for a month that has ended |
GET/v1/statements/:id | report:read | View a monthly certificate and its receipt list |
GET/v1/shares | share:admin | List shares |
POST/v1/shares | share:admin | Create a public share |
POST/v1/shares/:id/revoke | share:admin | Revoke a share; takes effect immediately |
GET/v1/public/shares/:id | – | View a public share |
GET/s/:id | – | Open a public share page |
Accounts, members and projects
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/members | members:admin | View members and the permissions for each role |
POST/v1/members | members:admin | Add a member; the key is returned only once |
PATCH/v1/members/:id | members:admin | Change a role; takes effect immediately |
POST/v1/members/:id/disable | members:admin | Disable a member and revoke their key |
POST/v1/members/:id/rotate-key | members:admin | Rotate a key; the old key stops working immediately |
POST/v1/api-keys | members:admin | Create a key for an app or agent; returned only once |
POST/v1/api-keys/:id/revoke | members:admin | Revoke a key |
POST/v1/projects | project:admin | Create a project |
GET/v1/projects/:id/settings | report:read | View project settings |
POST/v1/projects/:id/settlement-policy | budget:admin | Set the settlement amount and maximum wait |
POST/v1/projects/:id/fallback | project:admin | Set whether fallback estimates are allowed |
POST/v1/projects/:id/reestimate | project:admin | Re-estimate usage that could not be estimated before |
GET/v1/beneficiary-scopes | report:read | List beneficiary scopes |
POST/v1/projects/:id/beneficiary-scopes | project:admin | Create a beneficiary scope; use external_ref to avoid duplicates |
GET/v1/wallet-links | project:admin | List linked wallets |
POST/v1/wallet-links/challenges | project:admin | Get the text to sign when linking a wallet |
POST/v1/wallet-links | project:admin | Prove control with a signature and link a wallet; no transaction is sent |
POST/v1/wallet-links/:id/remove | project:admin | Unlink a wallet |
GET/v1/audit-log | members:admin | View the audit log |
Webhook
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/webhook-endpoints | webhook:admin | List webhook URLs |
POST/v1/webhook-endpoints | webhook:admin | Add a URL; the signing secret is returned only once |
POST/v1/webhook-endpoints/:id/rotate-secret | webhook:admin | Rotate the signing secret; the old one is still used to sign for 24 hours |
POST/v1/webhook-endpoints/:id/test | webhook:admin | Send a test notification |
POST/v1/webhook-endpoints/:id/disable | webhook:admin | Disable a URL |
GET/v1/webhook-deliveries | webhook:admin | View deliveries |
POST/v1/webhook-deliveries/:id/replay | webhook:admin | Replay a notification with the same ID |
Support tickets
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/support-tickets | read | List tickets |
POST/v1/support-tickets | read | Open a ticket |
GET/v1/support-tickets/:id | read | View a ticket and its replies |
POST/v1/support-tickets/:id/messages | read | Reply to or close a ticket |
Platform operations
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/ops/overview | ops:read | Source pools, supply and open issues |
GET/v1/ops/reconciliation | ops:read | Check the ledgers and on-chain records without changing data |
GET/v1/ops/batches | ops:read | View batches for all accounts |
POST/v1/ops/batches/:id/resolve | ops:write | Handle a batch with source problems |
POST/v1/ops/batches/:id/external-status | ops:write | Enter an external registration result |
GET/v1/ops/methodologies | ops:read | View all estimation methods |
POST/v1/ops/methodologies | ops:write | Publish a new version of an estimation method |
POST/v1/ops/source-pools/:id/price | ops:write | Change a source pool’s price; affects only new quotes |
GET/v1/ops/tenants | ops:read | View accounts and balances |
POST/v1/ops/tenants | ops:write | Create a personal or organization account |
POST/v1/ops/tenants/:id/fees | ops:write | Set the fees charged per match |
POST/v1/ops/tenants/:id/top-ups | ops:write | Top up test currency; each ID is posted only once |
POST/v1/ops/payment-orders/:id/refund | ops:write | Refund an unused top-up |
GET/v1/ops/audit-log | ops:read | View the operations activity log |
GET/v1/ops/support-tickets | ops:read | View all tickets |
GET/v1/ops/support-tickets/:id | ops:read | View one ticket |
POST/v1/ops/support-tickets/:id/messages | ops:write | Reply to or close a ticket |
Console queries
| Endpoint | Permission | Purpose |
|---|---|---|
GET/v1/overview | report:read | Overview |
GET/v1/usage-units | report:read | Deduplicated usage details |
GET/v1/usage-sources | report:read | Data sources |
GET/v1/matches | report:read | List of matches |
GET/v1/retirement-batches | report:read | Settlement batches |
GET/v1/fund-entries | billing:read | Funds activity |
GET/v1/admin/budget-grants | budget:admin | All grants for the tenant |
GET/v1/admin/api-keys | budget:admin | List of keys, without the keys themselves |
Sessions and service status
| Endpoint | Permission | Purpose |
|---|---|---|
POST/v1/session | – | Sign in to the console with an access key |
GET/v1/session | – | View the current key or session; requires authentication |
DELETE/v1/session | – | Sign out |
POST/v1/sandbox/settle | sandbox:admin | Run settlement manually; sandbox only |
GET/healthz | – | Check the service and its environment |
GET/openapi.json | – | Download the OpenAPI document |
GET/llms.txt | – | View instructions for agents |
GET/embed/v1.js | – | Load the embedded components |
Lists use cursor pagination. limit is 25 by default and can be up to 100. Use next_cursor from the response as the cursor for the next request. null means there is no more data. GET /v1/pending-usage does not use a cursor. Its limit is 100 by default and can be up to 500, and truncated means there is more usage that is not listed.
Error codes
Error responses look like this. The message in this example is in Chinese and means “The quote has expired”. Use code to handle errors. Do not rely on the text of message:
{
"error": {
"code": "quote_expired",
"message": "报价已过期"
}
}| HTTP | Code | Cause or what to do |
|---|---|---|
| 400 | invalid_request | The request format is invalid. Use issues to fix it |
| 400 | invalid_payment | The payment proof format is invalid |
| 400 | invalid_cursor | The pagination value is invalid. Start again from the first page |
| 401 | unauthorized | The key is missing or invalid |
| 401 | session_expired | Your console session has expired. Sign in again |
| 402 | payment_required | Pay as described in the PAYMENT-REQUIRED response header. See details.reason for the cause |
| 403 | wallet_not_linked | Link the wallet in the legacy record first |
| 403 | forbidden | The key does not have the required permission |
| 403 | bad_origin | A console write request has an invalid origin or header |
| 403 | grant_not_yours | The grant does not belong to the current key |
| 403 | grant_revoked | The grant has been revoked. Contact the account owner |
| 403 | grant_expired | The grant has expired. Contact the account owner |
| 403 | grant_scope_mismatch | The grant does not cover this project, beneficiary scope or source pool |
| 403 | budget_exceeded | The limit per match, per day or per month has been exceeded. Contact the account owner |
| 403 | buffer_not_allowed | The purchase buffer is higher than the grant allows |
| 403 | sponsorship_unavailable | The sponsorship has been revoked, has expired or does not apply to this beneficiary scope |
| 403 | scope_escalation | You cannot grant permissions you do not have |
| 404 | not_found | It does not exist or does not belong to the current tenant |
| 404 | sponsorship_code_invalid | The claim code is invalid, has expired or has already been used |
| 409 | event_conflict | The contents differ for the same revision. Increase revision when you make a change |
| 409 | identity_changed | A revision cannot change the request identifiers, provider or metering method |
| 409 | scope_conflict | The usage already belongs to another project or beneficiary scope |
| 409 | nothing_to_match | There is no electricity left to match |
| 409 | quote_used | The quote has already been used. Get a new one |
| 409 | quote_expired | The quote has expired. Get a new one |
| 409 | quote_mismatch | The usage events do not match the quote |
| 409 | quote_stale | Usage has changed since the quote. Get a new one |
| 409 | max_charge_exceeded | The quote is higher than max_charge |
| 409 | insufficient_funds | The account balance is too low |
| 409 | insufficient_inventory | The source pool does not have enough supply |
| 409 | idempotency_conflict | The request differs for the same idempotency key |
| 409 | plan_exists | The beneficiary scope already has an automatic plan. Edit or cancel that plan |
| 409 | plan_not_active | The plan is paused or has expired and cannot run |
| 409 | plan_cancelled | The plan has been cancelled and cannot be edited. Create a new one |
| 409 | scope_exists | The ID is already used for another type of beneficiary scope |
| 409 | member_disabled | The member has been disabled |
| 409 | last_manager | Keep at least one key that can manage members and does not expire |
| 409 | personal_account | Members cannot be added to a personal account |
| 409 | webhook_disabled | The webhook URL has been disabled. Create a new one |
| 409 | too_many_endpoints | You have reached the webhook URL limit. Disable one you no longer use |
| 409 | period_open | This month has not ended |
| 409 | connection_exists | This source has already been added |
| 409 | legacy_conflict | A legacy record with the same ID has different contents |
| 409 | methodology_exists | This version has already been published. Use a new version number |
| 409 | batch_not_resolvable | The batch does not need manual handling or is still being checked automatically |
| 409 | external_status_locked | An external registration result cannot be entered for this batch yet, or registration is already confirmed |
| 409 | order_expired | The payment order has expired. Create a new one |
| 409 | order_closed | The payment order has been refunded. Create a new one |
| 409 | order_not_refundable | Only orders that have been posted can be refunded |
| 409 | payment_in_progress | The previous payment has no result yet. Retry only that payment |
| 409 | payment_reused | The payment authorization has already been used for another order |
| 409 | payment_failed | The payment did not succeed. Get the payment requirements again |
| 409 | wallet_linked | The wallet is linked to another account. Unlink it there first |
| 409 | top_up_conflict | This ID has already been used for another top-up |
| 413 | report_too_large | There is too much data. Export each beneficiary scope separately |
| 422 | invalid_limits | Limits must be greater than 0, with per match ≤ daily ≤ monthly |
| 422 | invalid_expiry | The expiry must be in the future. Grants, plans, keys and sponsorships can last up to 366 days |
| 422 | invalid_usage | usage does not match usage_semantics |
| 422 | mixed_models | More than one model was used. Split the usage by model, then report it |
| 422 | not_metered | Rollup events cannot be matched |
| 422 | evidence_insufficient | There is no applicable estimation method |
| 422 | invalid_energy | The electricity value has an invalid format, precision or range |
| 422 | invalid_money | The amount of money has an invalid format or range |
| 422 | source_not_applicable | The year of use does not match the source’s generation year |
| 422 | invalid_attestation | The reporter signature is invalid, or the public key does not apply to this source |
| 422 | invalid_wallet_signature | Get new text to sign. Each text can be used only once |
| 422 | invalid_public_key | Provide an Ed25519 public key in PEM format. Never submit a private key |
| 422 | invalid_webhook_url | Only HTTPS URLs on the public internet are supported |
| 422 | invalid_effective_from | A method cannot take effect in the past |
| 410 | legacy_closed | Legacy Photosynth registration is no longer available. Use the new plugin |
| 500 | internal_error | An internal error occurred. Requests that support idempotency can be retried without changes |
Going over a rate limit returns HTTP 429. Errors handled by the framework, such as rate limits and oversized request bodies, all use the code request_error. Check the HTTP status code to tell them apart.
Batch reports return a result for each item. If an item returns internal_error, retry that item without changing it. Other errors must be fixed first.
TypeScript SDK
The SDK has no runtime dependencies and requires Node.js 22.12 or later. It can currently be used only inside the repository. Keep keys on the server and never use them in a browser.
| Feature | Methods |
|---|---|
| Account and environment | getSession, getEnvironment |
| Usage and estimates | reportUsage, reportUsageBatch, estimate, listMethodologies, listPendingUsage |
| Strict mode | getCoverageDecision |
| Quotes and matches | listSourcePools, listGrants, getBalances, createQuote, match, getMatch, waitForMatch |
| Receipts | getReceipt, verifyReceipt |
| Convert usage | fromAnthropicMessage, fromOpenAIResponse |
| Signatures | attestUsage, verifyWebhook |
| Local queue | enqueue and flush on UsageOutbox |
- All requests except
createQuoteare retried up to 2 times by default after a network error, timeout, 408, 429 or 5xx. If the server returnsRetry-After, the SDK waits for that long. If the wait is more than 30 seconds, it returns the error right away. - By default,
matchuses the quote ID to create its idempotency key. After a restart, retrying with the same arguments will not charge you twice. - When an error’s
outcomeUnknownistrue, the request may have been processed. Even if the last response was a 401, do not get a new quote or change the idempotency key. Fix the problem first, then retry with the same arguments. waitForMatchreturning does not mean the match succeeded. Checkclaim_statusto see whether it is complete.- Except on your local computer, only HTTPS is allowed. The SDK does not follow redirects, so keys are not sent to another address.
- Report every event returned by the conversion functions. Missing even one means usage is undercounted. For a streamed response, pass in the final result.
UsageOutbox saves each event as a file. enqueue returns only after the event is written to the local disk, and flush then sends it. Several processes can share a folder on the same computer, and the server removes any duplicates. Events that are clearly rejected are moved to rejected/, which you should check regularly. See Quick Start for a full example.
Python example
examples/python/arec_ai.py is a single-file client that uses only the standard library. It supports Python 3.10 or later and has been tested with 3.11, 3.12 and 3.13. It supports usage, quotes, matches, receipts and webhook signature checks. It does not have a persistent local queue, so save events yourself before reporting them. See examples/python/README.md for instructions.
MCP tools
The MCP server runs locally over stdio. It supports the 2026-07-28 protocol and is also compatible with the 2025 protocol versions.
| Tool | What it does | Spends money |
|---|---|---|
arec_get_status | View balances, grants, unmatched usage and plan status | No |
arec_estimate | Estimate electricity without recording usage | No |
arec_quote | Get a quote without reserving supply | No |
arec_match | Use an existing grant to accept a quote | Yes |
arec_get_receipt | Look up and verify a receipt | No |
arec_verify_receipt | Verify a receipt | No |
Once the arguments pass validation, every tool returns the same structure:
| Field | Meaning |
|---|---|
ok | Whether the tool call succeeded, not whether settlement is complete |
environment | Currently always sandbox |
settlement_complete | true only if the completion claim is valid and no checks have failed. It stays false if the match is confirmed on-chain but external registration is not complete. null means settlement does not apply |
next_action | none, request_quote, match_quote, check_receipt, retry_same_arguments, fix_arguments or ask_owner |
data / error | The data if the call succeeds, or the error code if it fails |
When error.outcome_unknown is true, the request may have been processed. Retry only with exactly the same arguments. Do not get a new quote.
MCP has no tools to create grants, raise budgets, top up, transfer money or call arbitrary contracts. ask_owner and the destructive label on arec_match are only hints. The server enforces the actual budget limits.
Photosynth collection
The Photosynth sandbox plugin reads local session records from Claude Code and Codex CLI, then reports usage through UsageOutbox. The hook only starts a background sync and does not wait for the network.
| Client | Metering source | Deduplicated by |
|---|---|---|
| Claude Code | message.usage in assistant records, including iterations | message.id |
| Codex CLI | token_usage_record, including usage from compaction | response_id |
- Usage is not lost if collection is interrupted: The reading position is saved only after events are added to the queue. Scanning again creates the same events.
- Usage can be updated: The revision is the total number of tokens plus 1, so an increase in usage replaces the earlier data.
- Codex totals are not counted as usage:
token_countmay repeat and does not include compaction. If an older version of Codex has no record for each request, the plugin warns that usage was missed. - Collection by project: Usage is collected only if it is allowed both by the rules when the response was created and by the current rules. If the folder cannot be identified, the usage is not collected. Paths are not reported.
- Sandbox only: The plugin will not send data to other environments. It also rejects keys with spending or admin permissions.
Session records use the clients’ internal formats, which may change. If a record type is renamed, the plugin may miss usage. It may warn you if it has not collected any usage for more than a day, but this is not guaranteed.
The plugin does not support Kimi. Records from kimi-cli have no stable response ID, and providers count tokens differently. They cannot be reliably deduplicated or converted into separate token categories.
Configuration and testing
| Environment variable | Default | Purpose |
|---|---|---|
DATABASE_URL | postgres://arec@127.0.0.1:54329/arec_sandbox | Application database |
TEST_DATABASE_URL | postgres://arec@127.0.0.1:54329/postgres | Used to create and delete test databases |
HOST | 127.0.0.1 | Address to listen on |
PORT | 4310 | Server port |
WORKER_INTERVAL_MS | 2000 | Wait between background settlement runs |
WEBHOOK_ALLOW_LOCAL | false | Allows webhooks to be sent to local addresses. Use only for local debugging |
SECURE_COOKIE | false | Must be true when using HTTPS |
The server does not read .env files automatically, so set environment variables before you start it. New database migrations are applied automatically at startup. Do not edit a migration that has already been applied. Add a new file for any changes.
pnpm typecheckpnpm testEach database test creates its own arec_test_* database and deletes it at the end. Tests also recalculate balances from the logs to check that the ledgers agree.
Real-chain adapter
src/chain/evm.ts is based on a fixed version of the ArkreenCore source code. It is not connected to the service. It does not read private keys or environment variables, and has no default contract addresses. Its tests use simulated RPC calls. They show only that it handles data as the source code does, not that a live deployment behaves the same way.
It calls offsetAndMintCertificate and writes the batch ID to the certificate. Before signing, it checks the chain, nonce, fees and contract arguments. After broadcasting, it reads the actual net amount and sources from on-chain logs and state. If anything does not agree, it stops and does not treat the transaction as successful.
Before it is enabled, at least these issues must be resolved:
- Beneficiary: The current interface has no beneficiary field, so each adapter can serve only one beneficiary. The certificate owner can still edit its details for 3 days after minting, so it must be monitored.
- Sources: ART uses sources from a shared queue, and some paths switch to bridged sources. Simulating a transaction first cannot lock in its sources, so a dedicated pool or a contract that can limit sources is required.
- Nonce: A dedicated account is required. If a signed nonce is used by another transaction, the adapter cannot currently replace the transaction or raise its fee automatically.
- Nodes: Outdated node data could temporarily move a confirmed batch back to an earlier state. Check that nodes are consistent and keep historical data, and confirm the chain’s finality rules.
- Locks: Preparing a transaction accesses a node while holding a database lock. Before connecting the adapter, change this to make the query first, then hold the lock only briefly.
- Different deployed version: In the public code used by the adapter, every NFT whose
idAssetis not 0 goes into the bridge queue. When checked, the ART contract on Polygon added only one specified type. Under the current rules, the source IDs of these NFTs in the normal queue would get a prefix. This could be treated as a source mismatch and stop processing, but it would not be wrongly reported as complete. Before enabling the adapter, update it for the deployed version and test it again. - Deployment: Fees, the minimum retirement amount and the source limit were checked on-chain once, but they may change. Check them again before enabling the adapter. Admin permissions and whether contracts are paused have not been verified, and the adapter has never been connected to a live deployment.
Not yet implemented
Real pilot
- Using a real chain, real assets and real payments, with custody for signing keys and on-chain accounts
- Evidence-based model energy coefficients, and checks on the reported values themselves
- Asset rights and source records, real matching rules, and automatic connections to external registries
- Data from the legacy Photosynth private backend, with checks on the imported results
Later stages
The design document lists these as optional or for later:
- Hourly matching, and dedicated estimators for images, video, training and edge meters. This usage can currently be reported as direct electricity data
- An on-chain
AllocationRegistryorBatchRetirement, after contract testing and an audit - Remote MCP, and publishing the SDK on npm and PyPI
Any remainder that has been retired but not allocated is only recorded separately. It will not be allocated again, so the batch manifests used by issued receipts do not change. The Photosynth plugin only collects usage. Matches are made by a plan on the server or an agent with a grant.
Production operations
- Custody and rotation for receipt signing keys, and a way for customers to hide or revoke receipts themselves
- Enterprise single sign-on, reverse proxy support, complete rate limiting, backups, monitoring and alerts
- An independent security audit
The number of confirmations, number of retries, fees and minimum retirement amount are sandbox settings. They must be checked again before connecting to a real chain.