Skip to content

Add QAGENT decentralized AI agent marketplace contract#814

Open
RideMatch1 wants to merge 1 commit intoqubic:developfrom
RideMatch1:feature/qagent-contract
Open

Add QAGENT decentralized AI agent marketplace contract#814
RideMatch1 wants to merge 1 commit intoqubic:developfrom
RideMatch1:feature/qagent-contract

Conversation

@RideMatch1
Copy link
Copy Markdown

@RideMatch1 RideMatch1 commented Mar 31, 2026

QAGENT: Decentralized AI Agent Infrastructure

Smart contract for on-chain AI agent task orchestration. Agents register with stake, accept tasks with escrow, submit results via commit-reveal, and earn reputation through successful completions. Disputes are resolved by arbitrator voting or escalated to the 676-computor oracle quorum via the AIVerify interface.

Task Lifecycle

Create (escrow) -> Accept (bond) -> Commit (hash) -> Reveal (data)
   -> Approve / Challenge -> Finalize / Dispute -> Oracle (if needed)

Three-Tier Verification

  1. Optimistic: Requester approves result directly
  2. Challenge: Challenger stakes bond, arbitrators vote (3-of-5)
  3. Oracle: AIVerify interface escalates to 676-computor quorum consensus

Procedures (29)

# Category Procedure
1-4 Agent Lifecycle RegisterAgent, UpdateAgent, DeactivateAgent, ReactivateAgent
5-7 Staking StakeMore, RequestUnstake, WithdrawStake
8-10 Services RegisterService, DeprecateService, UpdateServicePrice
11-20 Tasks CreateTask, AcceptTask, CommitResult, RevealResult, ApproveResult, ChallengeResult, FinalizeTask, TimeoutTask, CancelTask, CompleteMilestone
21-22 Oracle & Disputes RequestOracleVerification, CastDisputeVote
23, 28-29 Arbitrators RegisterArbitrator, DeactivateArbitrator, WithdrawArbitratorStake
24-25 Governance ProposeParameterChange, VoteOnProposal
26 Rating RateAgent
27 Delegation DelegateTask

Functions (9)

# Function
1-3 GetAgent, GetTask, GetService
4 GetPlatformStats
5-6 GetStake, GetArbitrator
7 GetAgentsByCapability
8 GetProposal
9 GetAgentReputationScore

State Size

Collection Type Capacity
agents HashMap<id, AgentRecord> 8,192
tasks HashMap<uint64, TaskRecord> 32,768
services HashMap<id, ServiceDefinition> 4,096
stakes HashMap<id, StakeRecord> 8,192
arbitrators HashMap<id, ArbitratorRecord> 256
interactions HashMap<id, uint32> 32,768
activeTaskQ Collection<uint64> 8,192
oracleQueryToTask HashMap<sint64, uint64> 8,192
proposalVoters HashMap<id, uint8> 8,192
proposals Array<GovernanceProposal> 64

Key Features

  • Commit-reveal: K12 hash verification prevents front-running
  • 5-tier reputation: Unranked -> Bronze -> Silver -> Gold -> Diamond (completion rate + unique requesters)
  • Progressive slashing: Bond burn -> registration stake slash -> suspension at 4+ offenses
  • Stake-weighted governance: 10 tunable parameters via proposal/vote
  • Fee distribution: Platform fee split to burn (50%), treasury (30%), arbitrator pool (20%)
  • Task delegation: Up to 3 levels deep with escrow tracking
  • Keeper incentives: External callers earn fees for triggering finalization/timeout
  • Execution fee sustainability: 15 burn points across slashing, fee splits, and governance burns

Oracle Integration: AIVerify

New oracle interface at index 3. Allows QAGENT to request that the computor quorum independently verify an AI agent's claimed result against a task specification. Fields: taskId, specHash, resultHash, modelHash, taskType. Reply: verdict (valid/invalid/abstain), confidence, verifiedHash.

Tests

96 Google Test cases covering:

  • Agent lifecycle (register, update, deactivate, reactivate, staking)
  • Full task workflow (create, accept, commit, reveal, approve, finalize)
  • Commit-reveal verification (K12 hash match/mismatch)
  • Challenge and dispute resolution (arbitrator voting, both verdicts)
  • Oracle callback handling (valid, invalid, failure fallback)
  • Progressive slashing and tier recalculation
  • Governance proposal lifecycle (propose, vote, execute, reject)
  • Task delegation with depth limits
  • Economic invariants (fee distribution, escrow conservation)
  • Edge cases (self-dealing, capacity limits, deadline enforcement)
  • Circuit breaker (paused state blocks operations)
  • END_TICK auto-processing (timeout, finalize, dispute cancel)

Verification

Check Result
contract-verify (v1.0.5) PASSED
ContractVerify CI PASSED (run 70963364499)
EFIBuild CI (MSVC x64 Release) PASSED (run 70963364512)
96/96 Google Tests PASSED
QPI compliance Zero violations
State access pattern 100% state.get() / state.mut()

Note on oracle input type: The oracle notification callback uses a using alias instead of typedef for OracleNotificationInput<AIVerifyOracle>. Both are semantically identical in C++; the alias form is used because contract-verify v1.0.5 does not yet resolve template typedefs (qubic-contract-verify#4, fix in PR#5).

Files Changed (10)

File Change
src/contracts/QAGENT.h NEW (3,809 lines)
src/oracle_interfaces/AIVerify.h NEW (95 lines)
test/contract_qagent.cpp NEW (3,931 lines)
src/contract_core/contract_def.h +20 lines (register index 27)
src/oracle_core/oracle_interfaces_def.h +10 lines (register AIVerify index 3)
test/CMakeLists.txt +1 line
src/Qubic.vcxproj +2 lines
src/Qubic.vcxproj.filters +6 lines
test/test.vcxproj +1 line
test/test.vcxproj.filters +1 line

All infrastructure file changes are pure additions (zero deletions).

Local Testnet

Unit tests cover all 29 procedures end-to-end (96/96 passing on MSVC x64). Local testnet testing with Core Lite pending (development machine is ARM-based, Core Lite requires x86 AVX2). Happy to test on x86 testnet infrastructure provided by the core team.

Construction Epoch

Set to 0 (placeholder). To be assigned by core team after proposal vote.

@fnordspace
Copy link
Copy Markdown
Contributor

Before I start the review of this Contract, please make sure it compiles and does not have any error when checking with https://github.com/Franziska-Mueller/qubic-contract-verify.

@RideMatch1 RideMatch1 force-pushed the feature/qagent-contract branch from 800d9bf to 4407762 Compare April 9, 2026 14:12
@RideMatch1
Copy link
Copy Markdown
Author

@fnordspace Thanks for the review request. Addressed both CI failures and rebased on latest develop.

Contract Verification

Ran qubic-contract-verify locally (latest main, commit 6068a48):

$ ./contractverify src/contracts/QAGENT.h
Contract compliance check PASSED

Changes since initial push

  1. ContractVerify fix: Replaced typedef OracleNotificationInput<AIVerifyOracle> with an explicit struct matching the same binary layout (workaround for qubic-contract-verify#4). Added static_assert to guarantee size parity at compile time.

  2. EFIBuild fix: Fixed MSVC C4018 signed/unsigned mismatch in test — EXPECT_LE(rep2.score, 10000u) (was comparing uint32 with int).

  3. Rebase: Rebased on current develop (f1c9611), resolved .vcxproj.filters merge conflict (kept both our AIVerify.h and upstream's custom_qubic_mining_storage.h entries).

Workflow runs need maintainer approval to execute (fork PR restriction).

@RideMatch1 RideMatch1 force-pushed the feature/qagent-contract branch 2 times, most recently from 7c3ad96 to 745b823 Compare April 9, 2026 15:59
@RideMatch1
Copy link
Copy Markdown
Author

Just to be clear about this contribution:

This is entirely free. I don't want money, tokens, grants, or any form of compensation. I built this purely because I believe in Qubic and want to see it succeed.

I've addressed all feedback from the contract verification check — it compiles, passes contractverify, all 96 tests pass, and it's rebased on current develop. CI just needs maintainer approval to run (standard fork PR restriction).

Let me put this into perspective: QAGENT is 3,800+ lines of production-grade smart contract code with a full test suite of 3,900+ lines. It implements three-tier dispute resolution with oracle escalation to the 676-computor quorum, stake-weighted governance, a five-tier reputation system, progressive slashing, commit-reveal task verification, and 29 procedures covering the complete agent lifecycle. This is not a toy contract. This is, to my knowledge, the most advanced smart contract ever written for Qubic — by a significant margin.

Qubic needs real infrastructure to be taken seriously as a platform. A decentralized AI agent marketplace is exactly the kind of unique, high-value application that sets Qubic apart. This contract is ready to go, it's been built to production standards, and it's being offered at zero cost.

I'm happy to answer any technical questions, walk through the architecture, or make adjustments based on review feedback. But I do need someone to actually look at it.

If the team decides this isn't something they want — that's completely fine, it's your call. But I'd ask that this at least gets a proper technical review before that decision is made. The work speaks for itself.

@RideMatch1 RideMatch1 force-pushed the feature/qagent-contract branch from 745b823 to 4a87934 Compare April 10, 2026 20:57
@RideMatch1
Copy link
Copy Markdown
Author

@fnordspace The C4018 signed/unsigned mismatch that caused the previous EFIBuild failures has been fixed — all uint32 comparisons in the test now use unsigned literals (0u, 10000u). The branch has also been rebased onto the latest develop (commit c22184f), all merge conflicts resolved.

However, since this is a fork PR, the CI workflows require maintainer approval to run. The last two workflow runs are stuck on action_required. Could you hit "Approve and run" on the Actions tab so CI can validate the fix?

TL;DR: Code is fixed and rebased. Just needs a click to run CI.

@RideMatch1
Copy link
Copy Markdown
Author

Status update on the open items from the previous review pass:

Build fix. The C4018: signed/unsigned mismatch that caused the EFIBuild failures on commits 4407762f and 7c3ad969 was traced to two EXPECT_GT/EXPECT_LE calls on QPI::uint32 fields (finalizedTick, score) using bare integer literals. Both are now instantiated as CmpHelperGT<uint32, unsigned int> via explicit 0u / 10000u suffixes, which resolves the warning under MSVC /warnaserror.

Rebase. The branch is rebased onto current develop (c22184f) with the contract_def.h conflict resolved. The NO_QAGENT feature guards wrap the include, registration descriptor, and REGISTER_CONTRACT_FUNCTIONS_AND_PROCEDURES call so the contract can be excluded from a build if ever needed.

Expanded test coverage. Since the last push, the suite has grown from 96 to 120 test cases, now the most extensive coverage of any contract in core. The additions target areas that were previously under- or un-tested:

  • The five return codes that had zero test coverage (AGENT_NOT_FOUND, DEADLINE_PASSED, ORACLE_PENDING, PROPOSAL_NOT_FOUND, SERVICE_NOT_FOUND) each now have at least one dedicated test
  • Authorization guards on CommitResult, RevealResult, ApproveResult, and DeprecateService are tested against non-privileged callers
  • Invalid state transitions (Commit on OPEN, Reveal on ACCEPTED, Approve on COMMITTED, CreateTask on a deactivated agent) are explicitly exercised
  • Fresh-contract invariants (query functions on empty state, zero-initialised platform stats, config seeded with compile-time constants) and registration-stake boundary conditions are covered

CI status. The post-fix runs on 745b8234, 4a879340, and the latest 4ea102c are all sitting on action_required because of the fork-PR approval gate — none of them have actually executed yet. Whenever you have a moment, approving the workflow on the latest commit would let CI validate the fix against the current state.

Happy to split the test additions into a separate commit series if that would make review easier.

@RideMatch1 RideMatch1 force-pushed the feature/qagent-contract branch from 4ea102c to d293829 Compare April 13, 2026 17:14
@RideMatch1
Copy link
Copy Markdown
Author

Rebased on latest develop (6505183) — merge conflicts in Qubic.vcxproj.filters and contract_def.h are resolved. Branch is clean and mergeable.

Both CI checks passed on the previous run (Apr 12), waiting for workflow approval on the new push.

Ready for review whenever you are, @fnordspace.

@Franziska-Mueller
Copy link
Copy Markdown
Collaborator

@RideMatch1 feel free to merge the newest develop into your branch to run the fixed version of the contract verification tool.

@RideMatch1 RideMatch1 force-pushed the feature/qagent-contract branch 2 times, most recently from 0ba2895 to 8521113 Compare April 15, 2026 15:33
@RideMatch1
Copy link
Copy Markdown
Author

Thanks @Franziska-Mueller! Just rebased on the latest develop which includes your oracle verification fix (#839).

Ran the updated contract-verify locally (v1.0.7) — all checks pass. I kept the using alias form since it works cleanly with both the old and new verifier versions. The typedef form still triggers the error due to the regex matching OI::* namespace prefix, while our oracle interface uses the AIVerifyOracle alias defined in oracle_interfaces_def.h. Not a big deal — both are identical to the compiler.

Branch is clean and up to date, ready for review whenever works for you @fnordspace.

@philippwerner
Copy link
Copy Markdown
Contributor

Thanks @RideMatch1 for your contribution. We will review the contract in detail soon. Please remove the using alias from oracle_interfaces_def.h. The contracts are supposed to use the OI::Name form for accessing the interfaces. If the contract verifier does not pass with this change, please push it anyway, because this will give us example code for fixing the verifier.

Copy link
Copy Markdown
Contributor

@fnordspace fnordspace left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @RideMatch1 for this PR. This is a first part of the review. Please note that we do not check the logic of the contract itself and mainly check for that the contract meets the requirements of a SC in Qubic. In this regard it looks quite good to me and i only pointed out a few small issues.
The arbitrator issue is not relevant for acceptance.

However I also struggle to understand the use of the Oracle at the moment. To my understanding this is only used for dispute resolution. However since tasks can be of a wide range how shall the oracle know how to answer the task? Maybe I miss something, tho.

Comment thread src/contract_core/contract_def.h Outdated
Comment thread src/contract_core/contract_def.h Outdated
Comment thread src/contracts/QAGENT.h Outdated
Comment thread src/contracts/QAGENT.h Outdated
Comment thread src/contracts/QAGENT.h
@RideMatch1 RideMatch1 force-pushed the feature/qagent-contract branch 2 times, most recently from 7524009 to 18c82a3 Compare April 15, 2026 17:32
@RideMatch1
Copy link
Copy Markdown
Author

Thanks @fnordspace and @philippwerner for the detailed review — really appreciate you taking the time!

All changes are in:

  • Contract index → 28 (adjusted for ESCROW)
  • Epoch → 212 (proposal 210, IPO 211, construction 212)
  • Empty BEGIN_TICK / BEGIN_EPOCH → removed
  • NO_QAGENT guards → removed (consistent with the ESCROW toggle removal)
  • Oracle aliases → removed from oracle_interfaces_def.h, contract now uses OI::AIVerify directly (matching the OI::Price pattern)
  • Arbitrator conflict-of-interest → added: assignedAgent, requester, and challenger are now excluded from dispute voting

On the oracle question (@fnordspace) — you're right that the oracle is most effective for deterministic tasks. The design is intentionally tiered:

  1. Tier 1 (optimistic) — requester approves directly. Handles everything, including subjective tasks.
  2. Tier 2 (challenge) — arbitrators vote. Works for disputes where human judgment is needed.
  3. Tier 3 (oracle) — computor quorum re-executes. This is where taskType and inferenceConfig matter: for DETERMINISTIC_INFERENCE (type 7), computors can independently reproduce the result and compare hashes. For open-ended types like GENERATE or SUMMARIZE, they can respond with verdict=0 (abstain), which causes the contract to fall back to arbitrator resolution.

So the oracle isn't meant to answer every task — it's a strong verification layer for tasks where deterministic reproduction is possible, and it gracefully degrades for everything else. Happy to add inline documentation to make this clearer in the code.

Ran the updated contract-verify (v1.0.7) locally — all checks pass with the OI::AIVerify form. Waiting for CI approval on the new push.

Smart contract for on-chain AI agent task orchestration. Agents register
with stake, accept tasks with escrow, submit results via commit-reveal,
and earn reputation through successful completions. Disputes are resolved
by arbitrator voting or escalated to the 676-computor oracle quorum via
the AIVerify interface.

- 29 procedures, 9 functions, 96 Google Test cases
- Three-tier verification: optimistic, challenge, oracle
- Commit-reveal with K12 hash verification
- 5-tier reputation system with progressive slashing
- Stake-weighted governance with 10 tunable parameters
- Task delegation up to 3 levels deep
- AIVerify oracle interface (index 3) for computor quorum consensus
- Contract index 28, construction epoch 212
@RideMatch1 RideMatch1 force-pushed the feature/qagent-contract branch from 18c82a3 to 3a5b78a Compare April 15, 2026 19:51
@RideMatch1
Copy link
Copy Markdown
Author

Fixed — was a typo in the new conflict-of-interest check (requesterIdrequester). Verified locally with contract-verify v1.0.7, all passing.

@fnordspace
Copy link
Copy Markdown
Contributor

Thanks for the update and explanation, contractend looks good to me so far. About the Oracle do plan to also provide the Oracle Machine part for this? https://github.com/qubic/oracle-machine

Also please do not force push anymore now that we startet the review because all references of open review points get distroyed with a force push.

@RideMatch1
Copy link
Copy Markdown
Author

Thanks @fnordspace! Good catch on the force-push — will only do regular commits from here on.

On the Oracle Machine: yes, that's the natural next step. The AIVerify interface on the contract side is the easier half — the harder part is the oracle implementation that actually runs the inference deterministically across the 676 computors. Looking at the existing oracles (price, doge_share_validation, mock) for reference patterns.

I don't want to promise a full ai_verify oracle plugin in this PR since it's a substantial separate piece of work (deterministic inference runtime, model loading, result comparison), but I'm planning to open a follow-up PR on qubic/oracle-machine once this contract lands. Happy to sketch out the architecture in a separate issue first if that would help align on approach.

Realistically the first version would support only DETERMINISTIC_INFERENCE tasks (type 7) where the oracle can reproduce and hash-compare. Non-deterministic types would continue to fall back to arbitrator resolution via Tier 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants