Repository navigation
Web Application Integration
- Introduction
- Project Structure
- Core Components
- Architecture Overview
- Detailed Component Analysis
- Dependency Analysis
- Performance Considerations
- Troubleshooting Guide
- Conclusion
- Appendices
This document explains how to integrate Sigvara into web applications using the TypeScript SDK. It covers frontend setup, configuration, initialization patterns, real-time reputation update strategies, user experience design for reputation displays and error handling, building reputation-gated interfaces, mobile and responsive considerations, cross-browser compatibility, security best practices, performance optimization, and caching strategies.
The Sigvara protocol provides computed reputation and staked accountability on top of ERC-8004 identity. The TypeScript SDK exposes agent identity, challenge-response authentication, on-chain reads, stake helpers, and a gate that turns reputation checks into actionable decisions.
Section sources
At a high level, the repository contains:
- Protocol documentation and quickstarts
- On-chain contracts and oracle logic
- The TypeScript SDK package with modules for agents, verifiers, gates, DID utilities, and types
For web integration, you primarily consume the SDK package and interact with the on-chain reputation system through RPC calls.
graph TB
subgraph "Web App"
FE["Frontend"]
BE["Backend Service"]
end
subgraph "Sigvara SDK"
IDX["SDK Index"]
AG["Agent"]
VR["Verifier"]
GT["Gate"]
TP["Types"]
end
subgraph "On-Chain"
ID["Identity Contract"]
RP["Reputation Contract"]
ST["Staking Contract"]
end
FE --> BE
BE --> IDX
IDX --> AG
IDX --> VR
IDX --> GT
IDX --> TP
VR --> ID
VR --> RP
VR --> ST
Diagram sources
- packages/sdk/src/index.ts:1-55
- packages/sdk/src/agent.ts
- packages/sdk/src/verifier.ts
- packages/sdk/src/gate.ts
- packages/sdk/src/types.ts
Section sources
- SigvaraAgent: Generates Ed25519 keys, derives DIDs, signs challenges, and issues challenges for peer verification.
- SigvaraVerifier: Reads identity, status, reputation, stake, verifies signatures, and builds DID documents from chain state.
- SigvaraGate: Issues challenges, enforces replay protection via nonces, validates proofs, checks active status, and compares matured scores against thresholds.
- Types: Shared interfaces for contract addresses, statuses, reputation data, challenges, and DID documents.
These components are exported from the SDK index and designed to be used by both backend services and frontends (with appropriate key management).
Section sources
- packages/sdk/src/agent.ts
- packages/sdk/src/verifier.ts
- packages/sdk/src/gate.ts
- packages/sdk/src/types.ts
- packages/sdk/src/index.ts:1-55
The typical flow for a web application is:
- Frontend requests access or performs an action requiring reputation gating.
- Backend uses SigvaraGate to issue a challenge bound to your service origin.
- Agent signs the challenge payload off-chain.
- Backend verifies the signature, ensures nonce uniqueness, checks agent activity, and compares the matured score to the threshold.
- UI renders gated content based on the decision.
sequenceDiagram
participant FE as "Frontend"
participant BE as "Backend"
participant Gate as "SigvaraGate"
participant Ver as "SigvaraVerifier"
participant Chain as "On-Chain Contracts"
FE->>BE : Request gated resource
BE->>Gate : challenge(agentDid)
Gate-->>BE : Challenge object
BE->>FE : Send challenge.payload
FE->>FE : Agent signs challenge.payload
FE->>BE : Return signature
BE->>Gate : admit(did, challenge, signature)
Gate->>Ver : verifySignature(...)
Ver->>Chain : Read identity + reputation
Chain-->>Ver : Identity, score
Ver-->>Gate : Verification result
Gate-->>BE : AdmitResult {ok, reason, score}
BE-->>FE : Allow or deny with reason
Diagram sources
- Install the SDK and ethers runtime dependency.
- Configure environment variables for RPC URL and chain ID.
- Initialize SigvaraVerifier with RPC URL, contract addresses, and chain ID.
- For agent-side flows, initialize SigvaraAgent with a securely stored private key and agent address.
Recommended steps:
- Use HTTPS-only endpoints.
- Store secrets in secure backends; never expose private keys to the browser.
- Use environment variables or secret managers for RPC URLs and contract addresses.
Section sources
- packages/sdk/README.md:7-11
- docs/quickstart.md:11-32
- packages/sdk/src/verifier.ts:32-42
- packages/sdk/src/agent.ts:15-25
Reputation updates are proposed by the oracle network and finalized after a challenge window. Consumers read the matured total score from the reputation contract.
Strategies:
- WebSocket or Server-Sent Events: Subscribe to events such as ScoreProposed, ScoreRejected, ReputationUpdated, then invalidate caches and re-render UI.
- Polling: Periodically call getTotalScore or meetsThreshold for active sessions.
- Event-driven cache invalidation: When a new score finalizes, refresh only affected agent profiles.
- The matured score also moves with time alone, so no event announces some changes. Poll for the current number and use events (including
AgentStatusUpdatedfor a change of status) to learn when to look again.
Implementation notes:
- Prefer reading the matured total score for threshold decisions.
- Cache results per agent DID with short TTLs during volatile periods (e.g., epoch boundaries).
- Debounce frequent UI updates to avoid layout thrashing.
Section sources
Displaying reputation:
- Show a badge or meter reflecting the current total score.
- For readers who want the detail behind a number, link to the public explorer: sigvara.xyz/agents lists every agent on Arc testnet with its score and stake and rechecks the evidence behind a score in the browser, and sigvara.xyz/epochs shows each proposal for one agent and what became of it. Agents run by Sigvara's testnet simulation are labelled "Simulated" there and counted apart; their activity is not outside demand.
- Indicate maturity: newly bonded agents may have earned points but not yet fully matured. Gate on the spendable score and show the earned score beside it if you want people to see that an agent is rising.
- Provide context: explain why a feature is gated (e.g., “Requires minimum reputation X”).
- Show the facts and the date they were read, and avoid wording that claims more than the data does, such as “Trusted by Sigvara”, “Verified safe”, “Audited”, “Insured” or “Guaranteed”. A score is not an audit, insurance or a guarantee.
Loading states:
- While fetching identity and reputation, show skeleton loaders.
- If RPC fails, display a retryable error with a brief explanation.
Error conditions:
- bad_proof: Ask the user to retry the authentication flow.
- replayed: Prompt for a fresh challenge.
- not_active: Explain that the agent is unbonded (or bonded below the current minimum stake), suspended, or slashed.
- stale_score: Only if you set
maxScoreAgeSeconds. Say the score has not been refreshed recently, and tell your operators, because the oracle may have stopped writing. - below_threshold: Show the current score and required threshold; optionally link to guidance on improving reputation.
Section sources
Use SigvaraGate to make consistent admission decisions:
- Issue a challenge bound to your service origin.
- Validate the returned signature.
- Enforce nonce uniqueness to prevent replays.
- Check agent activity and the bond held now (alpha.9 checks the stored status only), and compare the matured score to your threshold.
UI rendering:
- Conditionally render features based on AdmitResult.ok.
- Surface the specific reason when denied to guide users.
- Avoid exposing internal implementation details; translate reasons into user-friendly messages.
flowchart TD
Start(["Start Admission"]) --> Issue["Issue Challenge"]
Issue --> Sign["Agent Signs Payload"]
Sign --> Verify["Verify Signature"]
Verify --> Valid{"Valid?"}
Valid --> |No| BadProof["Return 'bad_proof'"]
Valid --> |Yes| Nonce["Check Nonce Uniqueness"]
Nonce --> Replay{"Replayed?"}
Replay --> |Yes| Replayed["Return 'replayed'"]
Replay --> |No| Active["Check Agent Active and Bonded"]
Active --> IsActive{"Active and bonded?"}
IsActive --> |No| NotActive["Return 'not_active'"]
IsActive --> |Yes| Score["Read Matured Total Score"]
Score --> Fresh{"Too old? Only if maxScoreAgeSeconds is set"}
Fresh --> |Yes| Stale["Return 'stale_score' with score"]
Fresh --> |No| Threshold{"Meets Threshold?"}
Threshold --> |No| Below["Return 'below_threshold' with score"]
Threshold --> |Yes| Allow["Allow Access"]
Diagram sources
Section sources
- Use responsive layouts to adapt badges and meters across screen sizes.
- Minimize heavy computations on-device; delegate cryptographic operations to secure backends where possible.
- Handle intermittent connectivity gracefully: queue actions, retry with exponential backoff, and preserve user intent.
- For mobile wallets or embedded browsers, ensure proper CORS and HTTPS policies.
- Ensure Ed25519 libraries and base58 encoding work consistently across browsers.
- Test challenge signing flows in Safari, Chrome, Firefox, and mobile browsers.
- Validate nonce and timestamp handling under different time zones and daylight saving transitions.
- Never store private keys in the browser; use secure backends or hardware-backed signers.
- Require HTTPS for all endpoints and RPC connections.
- Bind challenges to a stable audience (your origin) to prevent relay attacks.
- Have the agent sign with
signChallengeFor(payload, audience), passing the origin it connected to. It signs only a challenge addressed to that audience, so the binding protects the agent as well as the server. The agent'ssignChallenge, which signed whatever it was handed, is removed in 1.0.0-alpha.12 (1.0.0-alpha.9 has onlysignChallenge). - Implement robust nonce storage with atomic consume semantics for distributed deployments, such as
atomicNonceStoreover a RedisSET NX, and setinstances: 'multiple'so the gate refuses to start without it. In production,profile: 'production'makes the gate refuse to start untilinstancesandmaxScoreAgeSecondsare set. - Sanitize inputs and validate signature lengths before decoding to avoid DoS.
- Rate-limit the endpoint that calls
gate.admit: anyone who can form a well-sized signature for a registered agent makes the gate read that agent's key from chain. - Limit exposure of contract addresses and RPC endpoints to necessary scopes.
Section sources
- Cache reputation data per DID with short TTLs; invalidate on events or periodic refresh.
- Prefer getTotalScore over getReputation when only threshold checks are needed to reduce contract reads.
- Batch UI updates and debounce frequent changes.
- Use optimistic UI for non-critical paths while waiting for on-chain confirmation.
- Monitor RPC rate limits and implement retries with jitter.
- The verifier and the gate abandon a chain read after 30 seconds by default;
timeoutMschanges that (alpha.9 waits the five minutes ethers allows).
Section sources
The SDK exports a cohesive set of modules:
- Agent handles key generation and challenge signing.
- Verifier performs on-chain reads and signature verification.
- Gate orchestrates admission logic with nonce management.
- Types define shared structures.
classDiagram
class SigvaraAgent {
+generate(options)
+issueChallenge(peerDid, ttlSeconds)
+signChallengeFor(payload, audience)
+did
+didHash
+publicKeyBytes32
}
class SigvaraVerifier {
+getIdentity(did)
+isActive(did)
+getReputation(did)
+getTotalScore(did)
+getScoreUpdatedAt(did)
+meetsThreshold(did, threshold)
+verifySignature(did, payload, signature, maxAgeSeconds, expectedAudience)
+buildDidDocument(did)
}
class SigvaraGate {
+challenge(did)
+admit(did, challenge, signature)
-consumeNonce(nonce, expiresAt, nowSeconds)
}
class Types {
<<interface>>
ContractAddresses
AgentStatus
ReputationData
Challenge
ParsedChallenge
VerifierConfig
DidDocument
VerificationMethod
}
SigvaraGate --> SigvaraVerifier : "uses"
SigvaraAgent --> Types : "exports types"
SigvaraVerifier --> Types : "exports types"
Diagram sources
- packages/sdk/src/agent.ts
- packages/sdk/src/verifier.ts
- packages/sdk/src/gate.ts
- packages/sdk/src/types.ts
Section sources
- Prefer matured score checks for consistency with on-chain behavior.
- Reduce redundant reads by caching identity and reputation per session.
- Use event-driven updates to minimize polling overhead.
- Profile RPC latency and adjust TTLs accordingly.
- Avoid heavy client-side cryptography; delegate to secure backends when feasible.
Common issues and resolutions:
- bad_proof: Verify the challenge payload, signature format, and audience binding.
- replayed: Ensure unique nonces and implement atomic consume semantics.
- not_active: Confirm the agent is bonded and active; check staking and slashing status, and that its bond still meets the current minimum stake (alpha.9 does not check the bond).
- stale_score: Check that the oracle is running and finalizing scores (only with
maxScoreAgeSeconds). - below_threshold: Compare the matured total score to the configured threshold; consider adjusting UI messaging.
Operational tips:
- Log AdmitResult.reason to diagnose failures without exposing sensitive data.
- Monitor nonce store health and prune expired entries regularly.
- Validate signature length and alphabet before decoding to prevent crashes.
Section sources
- packages/sdk/src/gate.ts:32-53
- packages/sdk/src/gate.ts:282-298
- packages/sdk/src/verifier.ts:197-224
Integrating Sigvara into web applications involves setting up the SDK, initializing verifier and agent instances, issuing and verifying challenges, and gating UI elements based on matured reputation scores. By following the recommended UX patterns, security practices, and performance optimizations, you can build robust, reputation-aware interfaces that scale across devices and browsers while maintaining strong security guarantees.
- Install the SDK and ethers.
- Set environment variables for operator key, RPC URL, and testnet addresses.
- Generate an Ed25519 keypair, register the agent, deposit stake, and verify registration.
- Use SigvaraVerifier to read identity and reputation.
Section sources
- Six factors contribute to the total score, including fee activity, success rate, tenure, external trust, community flags, and propagation.
- Only bonded agents are scored; maturity controls spendability.
- Slashing resets reputation and terminates the agent’s lifecycle.
Section sources
- Agent Registration and Lifecycle
- Contract Overview and Architecture
- Economic Security Model and Incentives
- Evidence Verification and Merkle Proofs
- Key Management and Rotation
- Maturity Mechanism and Score Release
- Proposal Workflow and Challenge System
- Score Storage and Data Model
- SigvaraIdentity Contract
- SigvaraOracleBond Contract
- SigvaraReputation Contract
- SigvaraStaking Contract
- Slashing Lifecycle and Dispute Resolution
- Stake Management Functions
- Status Management and Control
- Token and Fee Contracts
- Unbonding Period and Withdrawal Security
- Anti-Manipulation and Security Measures
- Community Flag Processing
- Evidence Sources and Verification
- External Trust Integration
- Merkle Proof System
- Oracle Score Computation
- Payment-Backed Attestations
- Scoring Model and Formulas
- Agent Creation and Key Management
- Agent Operations
- Agent Registration Workflow
- Challenge-Response Authentication
- Gate Access Control
- Integration Patterns and Examples
- SDK Overview and Setup
- Verifier Functions