SDK API reference.

The complete @adunai/sdk namespace reference: every one of the 35 namespaces the client exposes (timelock included), each with its real reads, writes, events, and EIP-712 typed-data builders. In-repo under Apache-2.0; npm publication lands with the Phase 1 public release.

This reference is generated against the SDK source. Namespaces map to the deployed contracts documented in the contract registry. For task-oriented walkthroughs see the @adunai/sdk and @adunai/verify recipe pages and the builder hub. All calls are testnet-guarded in Phase 0.

identity

Wraps IdentityRegistry (Layer 1 DID anchoring). DID resolution, registration, key rotation, and recovery-config triggering. Constructed via createIdentityNamespace(ctx); reads and writes are spread onto the namespace, events under .events.

Reads

  • resolve(did): full identity record (controllingKey, registeredAt, lastKeyRotation, revoked, recoveryConfigHash); null if unregistered.
  • isControlledBy(did, key): true iff key is the current controlling key of an unrevoked, registered DID.
  • nonceOf(signer): EIP-712 nonce in IdentityRegistry's nonce space (independent of Handle/Attestations spaces).
  • deriveDID(salt, initialKey): recompute the canonical DID for a (salt, initialKey) pair via the contract.
  • getRecoveryConfig(did): convenience read of just the recovery-config hash; null if unregistered.

Writes

  • register({ salt, initialKey, recoveryConfigHash, registrationFee? }): direct call; registers a new DID, decodes to { did }.
  • prepareRotateKey({ did, newKey, deadline, currentKey }): sig-bearing; returns { typedData, signer, submit } where submit({ signature }) yields a TxBuilder for rotateKey.
  • applyRecoveryConfig(did): permissionless trigger; applies a queued recovery-config change after its 48h timelock.

Events

  • events.getIdentityRegistered({ fromBlock?, toBlock?, did?, controllingKey? }): historical IdentityRegistered, authenticated by construction (verified: true).
  • events.getKeyRotated({ fromBlock?, toBlock?, did? }): historical KeyRotated, authenticated by the EIP-712 signature requirement.

EIP-712 typed data

  • buildRotateKeyTypedData(domain, { did, newKey, nonce, deadline }): RotateKey digest.
  • buildSetRecoveryConfigTypedData(domain, { did, newConfigHash, nonce, deadline }): SetRecoveryConfig digest.
  • buildRevokeIdentityTypedData(domain, { did, reasonHash, nonce, deadline }): Revoke digest.

handles

Wraps HandleRegistry (human-readable names bound to DIDs; BASE tier plus INSTITUTIONAL verified-tick tier). Registration, renewal, transfer, primary-handle pointers, and verifier authorization. Phone resolution is fail-closed via CanonicalName.fromPhone, there is no findByPhone.

Reads

  • resolveCanonical(canonicalName): full handle record; null if never registered.
  • handlesOf(did): all canonical names bound to a DID (may include expired).
  • primaryHandleOf(did): the DID's primary-handle pointer; null when unset.
  • isVerified(canonicalName): institutional-verification status (verified, institutionType, verifiedUntil); always an object.
  • isReserved(canonicalName): reserved-name record; null when not reserved.
  • isAuthorizedVerifier(verifier, institutionType): verifier authorization status; null when not authorized.
  • pendingRevocationOf(canonicalName): pending institutional revocation; null when none.
  • baseFee(nameLength, durationYears): required BASE-tier registration fee.
  • nonceOf(signer): EIP-712 nonce in HandleRegistry's nonce space.
  • paused(): whether user-facing operations are paused.
  • maxDurationYears(): current cap on registration duration.

Writes

  • registerHandle({ canonicalName, did, durationYears, fee? }): direct call; auto-computes fee from baseFee() if omitted; decodes to { expiresAt }.
  • renewHandle({ canonicalName, durationYears, fee? }): permissionless direct call; auto-fee if omitted.
  • prepareTransferHandle({ canonicalName, newDid, deadline, currentOwnerDid }): sig-bearing; resolves the owner key via the identity seam, returns { typedData, signer, submit } for transferHandle.
  • authorizeVerifier({ verifier, institutionType, authorizationExpiry }): governance (VERIFIER_ADMIN_ROLE); expiry must be at least now + 90 days.
  • prepareRegisterInstitutional({ canonicalName, did, institutionType, verifiedUntil, evidenceHash, durationYears, deadline, fee? }): sig-bearing; DID key consents, an authorized verifier submits; submit({ didConsentSignature }) decodes to { verifiedUntil }.
  • prepareSetPrimaryHandle({ did, canonicalName, deadline, currentKey }): sig-bearing; submit({ signature }) for setPrimaryHandle.
  • prepareClearPrimaryHandle({ did, deadline, currentKey }): sig-bearing owner-signed clear; submit({ signature }) for clearPrimaryHandle.
  • clearPrimaryHandleIfStale(did): permissionless cleanup of a stale primary-handle pointer (empty signature path).

Events

  • events.getHandleRegistered({ fromBlock?, toBlock?, canonicalName?, did?, registrar? }): HandleRegistered.
  • events.getHandleRenewed({ fromBlock?, toBlock?, canonicalName?, payer? }): HandleRenewed.
  • events.getHandleTransferred({ fromBlock?, toBlock?, canonicalName?, fromDid?, toDid? }): HandleTransferred.
  • events.getHandleOverwritten({ fromBlock?, toBlock?, canonicalName?, previousDid? }): HandleOverwritten.
  • events.getPrimaryHandleSet({ fromBlock?, toBlock?, did?, canonicalName? }): PrimaryHandleSet.
  • events.getPrimaryHandleCleared({ fromBlock?, toBlock?, did?, previousCanonicalName? }): PrimaryHandleCleared; each event carries a lazy resolveClearedBy() returning 'owner' | 'staleness-cleanup'.

EIP-712 typed data

  • buildTransferHandleTypedData(domain, { canonicalName, newDid, nonce, deadline }): TransferHandle digest.
  • buildSetPrimaryHandleTypedData(domain, { did, canonicalName, nonce, deadline }): SetPrimaryHandle digest.
  • buildClearPrimaryHandleTypedData(domain, { did, nonce, deadline }): ClearPrimaryHandle digest.
  • buildRegisterInstitutionalTypedData(domain, { canonicalName, did, institutionType, verifiedUntil, evidenceHash, durationYears, nonce, deadline }): RegisterInstitutionalByDID consent digest.

Helpers and parser

  • isLive(record, { now? }): pure helper; true when now <= expiresAt (ignores grace period).
  • gracePeriodStatus(record, { now?, gracePeriodSeconds? }): pure three-state 'live' | 'grace' | 'expired'.
  • Handle.parseDisplay('alice.adunai' | 'ecobank.bank.adunai'): display-form parser (also exported as ParsedHandle type).

Constants

  • GRACE_PERIOD_SECONDS: 2_592_000n (30 days) before an expired handle becomes overwriteable.
  • MIN_NAME_LENGTH: 3 UTF-8 bytes.
  • MAX_NAME_LENGTH: 32 UTF-8 bytes.
  • INSTITUTIONAL_SUBDOMAINS: display token to InstitutionType map (bank, gov, health, edu, org, telco, utility, press).
  • INSTITUTION_TYPE_TO_SUBDOMAIN: inverse map, enum value to display token.
  • ADUNAI_SUFFIX: 'adunai'; all display forms end in .adunai.

revocation

Wraps RevocationRegistry (multi-key lifecycle: DID and per-key revocation, add-key, rotation and scheduled rotation, primary-key selection, guardian and vouch quorum revocation, self-revoke DID with cooling-off, and override reconciliation). Value-flow consumers resolve keys through this registry's override-aware views.

Reads

  • isDIDRevoked(did): whether the DID is revoked.
  • getDIDRevocation(did): DID revocation status (isRevoked, revokedAtTimestamp, revokedVia, reasonHash).
  • isKeyRevoked(did, key): whether a specific key is revoked.
  • getKeyRevocation(did, key): key revocation status (isRevoked, revokedAtTimestamp, revokedVia).
  • isActiveKey(did, key): whether a key is currently active for the DID.
  • getActiveKeys(did): array of active keys.
  • getPrimaryKey(did): the DID's primary key.
  • effectiveValueKey(did): override-aware key used for value-flow authorization.
  • getScheduledRotation(did): pending scheduled rotation (newKey, oldKey, effectiveTimestamp).
  • pendingSelfRevokeOf(did): pending self-revoke-DID cooldown (cooldownInitiatedAt, cooldownExpiresAt, reasonHash).
  • nonceOf(signer): EIP-712 nonce for a signer.
  • isBootstrapped(did): whether the DID's key set is bootstrapped in this registry.
  • vouchQuorumThreshold(): M-of-N vouch quorum threshold (as number).
  • vouchQuorumRecencyWindow(): recency window for counting vouches toward quorum.
  • lastReconciledGeneration(did): last override generation reconciled for the DID.

Writes

  • selfRevokeKey({ did, keyToRevoke }) / prepareSelfRevokeKey({ did, keyToRevoke, deadline }): direct and sig-bearing (selfRevokeKeyBySignature).
  • selfRevokeDID({ did, reasonHash }) / prepareSelfRevokeDID({ did, reasonHash, primaryKey, deadline }): initiate self-revoke DID (direct or by signature); enters cooling-off.
  • cancelSelfRevokeDID({ did }): cancel a pending self-revoke-DID cooldown.
  • finalizeSelfRevokeDID({ did }): finalize after the cooldown elapses.
  • guardianQuorumRevokeKey({ did, keyToRevoke, guardianDids, guardianSignatures, deadline }): M-of-N guardian revoke.
  • prepareGuardianRevokeKey({ did, keyToRevoke, guardianDid, deadline }): build the per-guardian typed data; returns { typedData, signer, nonce } (no single-sig submit).
  • vouchQuorumRevokeKey({ did, keyToRevoke, voucherDids, voucherSignatures, deadline }): M-of-N vouch revoke.
  • prepareVouchRevokeKey({ did, keyToRevoke, voucherDid, deadline }): build the per-voucher typed data; returns { typedData, signer, nonce }.
  • rotateKey({ did, oldKey, newKey }) / prepareRotateKey({ did, oldKey, newKey, deadline }): immediate rotation (direct or rotateKeyBySignature).
  • addKey({ did, newKey }) / prepareAddKey({ did, newKey, signer, deadline }): add a key (direct or addKeyBySignature).
  • scheduleRotation({ did, oldKey, newKey, effectiveTimestamp }) / prepareScheduleRotation({ ..., signer, deadline }): schedule a future rotation (direct or by signature).
  • applyScheduledRotation({ did }): apply a scheduled rotation once effective.
  • cancelScheduledRotation({ did }): cancel a scheduled rotation.
  • setPrimaryKey({ did, newPrimaryKey }) / prepareSetPrimaryKey({ did, newPrimaryKey, signer, deadline }): set the primary key (direct or setPrimaryKeyBySignature).
  • reconcileToOverride({ did }): reconcile the key set to a recovery override.

Events

  • events.getKeyRevoked, getDIDRevoked, getKeyAdded, getPrimaryKeySet, getRotationScheduled, getRotationApplied, getRotationCancelled: each takes { fromBlock?, toBlock?, did? }.
  • events.getSelfRevokeDIDCooldownInitiated, getSelfRevokeDIDCooldownCancelled, getSelfRevokeDIDCooldownFinalized: self-revoke cooldown lifecycle, same filter shape.
  • events.getReconciledToOverride({ fromBlock?, toBlock?, did? }): override reconciliation.

EIP-712 typed data

  • buildSelfRevokeKeyTypedData(domain, { did, keyToRevoke, nonce, deadline }): SelfRevokeKey.
  • buildSelfRevokeDIDTypedData(domain, { did, reasonHash, nonce, deadline }): SelfRevokeDID.
  • buildRotateKeyTypedData(domain, { did, oldKey, newKey, nonce, deadline }): RotateKey.
  • buildAddKeyTypedData(domain, { did, newKey, nonce, deadline }): AddKey.
  • buildScheduleRotationTypedData(domain, { did, oldKey, newKey, effectiveTimestamp, nonce, deadline }): ScheduleRotation.
  • buildSetPrimaryKeyTypedData(domain, { did, newPrimaryKey, nonce, deadline }): SetPrimaryKey.
  • buildGuardianRevokeKeyTypedData(domain, { did, keyToRevoke, guardianDid, nonce, deadline }): GuardianRevokeKey.
  • buildVouchRevokeKeyTypedData(domain, { did, keyToRevoke, voucherDid, nonce, deadline }): VouchRevokeKey.

linkedIdentities

Wraps LinkedIdentitiesRegistry (user-controlled linkage of multiple DIDs into one graph, for multiple SIMs, shared devices, or diaspora signups). Mutual-consent and abandonment link paths, timelocked unlinkage, and effective key / KYC-tier resolution across the graph.

Reads

  • isLinked(didA, didB): whether an active linkage exists between the pair.
  • linkedDIDs(did): direct-neighbor DIDs linked to the given DID (not transitive).
  • getLinkageCommitment(linkageId): { commitment, commitmentType: 'KECCAK' } for an active linkage.
  • getUnlinkageStatus(didA, didB): pending unlinkage state (pending, initiatedAt, expiresAt).
  • getCurrentNonce(didA, didB): monotonic per-pair linkage nonce.
  • effectiveControllingKey(did): effective controlling key integrating identity and abandonment layers.
  • effectiveKycTier(did): { tier, inCoolingOff }, accounting for the KYC cooling-off window.
  • getMaxLinkageGraphSize(): max DIDs per graph (MAX_LINKAGE_GRAPH_SIZE, 5 inclusive).
  • getUnlinkageTimelock(): timelock before an initiated unlinkage may finalize (30 days).
  • getUnlinkageCooldown(): cooldown before re-initiating unlinkage on the same pair (7 days).
  • getKycCooloffDuration(): KYC-tier cooling-off after a tier increase via linkDID (14 days).
  • getAbandonmentFreshnessWindow(): abandonment-proof freshness window (30 days).

Writes

  • prepareLinkDID({ primaryDID, secondaryDID, salt, deadline, abandonmentClaimRef? }): sig-bearing; returns { typedData, secondaryAbandonmentConsentData?, submit }. Mutual path uses both signatures; supplying abandonmentClaimRef selects the abandonment path (adds a secondary consent digest). submit({ primarySignature, secondarySignature }) decodes to { linkageId }.
  • unlinkDID(primaryDID, secondaryDID): direct call by a controller of either DID; starts the 30-day timelock.
  • cancelUnlinkage(primaryDID, secondaryDID): direct call; only the initiator may cancel.
  • finalizeUnlinkage(primaryDID, secondaryDID): permissionless trigger once the timelock elapses.

Events

  • events.getAll({ fromBlock?, toBlock?, linkageId? }): block-sorted union of all four event types.
  • events.getLinkageCreated({ fromBlock?, toBlock?, linkageId?, primaryDID?, secondaryDID? }): LinkageCreated.
  • events.getUnlinkageInitiated({ fromBlock?, toBlock?, linkageId? }): UnlinkageInitiated.
  • events.getUnlinkageCancelled({ fromBlock?, toBlock?, linkageId? }): UnlinkageCancelled.
  • events.getUnlinkageFinalized({ fromBlock?, toBlock?, linkageId? }): UnlinkageFinalized.

EIP-712 typed data

  • buildLinkDIDTypedData(domain, { primaryDID, secondaryDID, linkageNonce, deadline }): LinkDID digest (shared across mutual and abandonment paths).
  • buildLinkAbandonmentConsentTypedData(domain, { secondaryDID, primaryDID, proofPath, linkageNonce, deadline }): LinkAbandonmentConsent digest; proofPath is 'mutual' | 'abandonment'.

attestations

Wraps AttestationsRegistry (Layer 2 trust model, Layer B). Typed, signed claims about a DID: issue, revoke, and release attestations under registered schemas, with a hybrid client-side preflight and four EIP-712 signing paths. Assembled via createAttestationsNamespace(ctx), spreading reads and writes with .events plus the pure helpers.

Reads

  • getAttestation(attestationId): full record plus live valid flag; null when never issued.
  • isValid(attestationId): on-chain live-validity check.
  • hasValidAttestation(subjectDid, schema): true if subject holds at least one valid attestation under the schema.
  • getSchema(schema): schema metadata; null when the schemaId was never registered.
  • attestationsOf(subjectDid, schema): attestation ids about a subject under a schema (may include revoked/expired).
  • issuancesOf(issuerDid): attestation ids issued by an issuer across all schemas.
  • isAccredited(schema, issuerDid): issuer in the accredited set for an ACCREDITED-policy schema.
  • isRestrictedVerifier(schema, issuerDid): restricted-verifier status with authorizationExpiry; null when not authorized.
  • isSuspended(schema, issuerDid): issuer suspended for the schema.
  • activeAttestationCountOf(subjectDid, schema): active (non-revoked, non-released) count at (subject, schema).
  • isSchemaDeprecated(schema): schema deprecation flag.
  • requiresSubjectConsent(schema): whether the schema requires a subject EIP-712 consent signature.
  • nonceOf(signer): this registry's independent EIP-712 nonce for a signer.
  • paused(): whether user-facing operations are paused.

Writes

  • issueAttestationAsIssuer(opts): direct-caller issue (no consent); throws ConsentRequiredError if the schema needs consent. Decodes { attestationId }.
  • issueAttestationAsIssuerWithConsent(opts): direct-caller issue carrying a subject EIP-712 consent signature.
  • revokeAttestationAsIssuer(opts): revoke your own attestation as the issuer's controlling key.
  • prepareIssueAttestation(opts): off-chain issuer signature path; returns { typedData, signer, schemaId, submit }.
  • prepareSubjectConsent(opts): subject-consent EIP-712 payload; returns { typedData, signer, schemaId } (distinct typehash from issuance).
  • prepareRevokeAttestation(opts): off-chain issuer revocation signature; returns { typedData, signer, submit }.
  • prepareReleaseAttestation(opts): subject release signature reclaiming a per-schema slot; returns { typedData, signer, submit }.
  • issueAttestationWithSignatures(opts): pure-bytes composition helper for pre-assembled issuer/subject signatures.

Events

  • events.getAttestationIssued(opts): AttestationIssued logs; each carries a lazy resolveIssuanceMode() discriminating the four issuance modes.
  • events.getAttestationRevoked(opts): AttestationRevoked logs; each carries a lazy resolveRevocationMode() (direct/signed/batch-foundation).
  • events.getReleasedBySubject(opts): ReleasedBySubject logs (single path, no discriminator).

EIP-712 typed data

  • buildIssueAttestationTypedData(domain, message): issuer's off-chain issuance signature.
  • buildIssueAttestationBySubjectTypedData(domain, message): subject's consent signature (same shape, different typehash).
  • buildRevokeAttestationTypedData(domain, message): issuer's off-chain revocation signature.
  • buildReleaseAttestationTypedData(domain, message): subject's slot-release signature.

Pure helpers

  • isAttestationLive(attestation, opts?): off-record liveness check (revoked/released/expiry), no RPC.
  • attestationStatus(attestation, opts?): discriminated status (live/expired/revoked/released/unknown).
  • resolveSchemaRef(ref): normalize a SchemaRef (bare id or { id, name? }) to a SchemaId.

Constants

  • MAX_BATCH_REVOCATION_SIZE = 100: max batch size for the Foundation batch-revoke path.
  • MIN_VERIFIER_AUTH_DURATION_SECONDS = 2_592_000n (30 days).
  • MIN_INITIAL_MAX_EXPIRY_DELTA_SECONDS = 315_360_000n (3650 days), initial floor reference.
  • ACTIVE_COUNT_SATURATION = 65_535: saturation value for the per-(subject, schema) active counter.

identity-attestations

Wraps IdentityAttestations (Layer 2, Layer B), the attester-keyed key-value attestation store parallel to AttestationsRegistry. Splits the per-subject surface into a BENIGN band (requires an EIP-712 subject consent) and a governed ADVERSE band (pep./aml./sanctions. family prefixes, issued without consent under regulator accreditation). Assembled via createIdentityAttestationsNamespace(ctx).

Reads

  • getAttestation(attestationId): full record; null when never populated.
  • isValid(attestationId): exists, unrevoked, unexpired, and creating attester still authorized.
  • isAdverseMethod(methodId): pure-string check whether a method matches a governed adverse family prefix.
  • activeAdverseCountOf(subjectDid): active adverse-band count (reclaimable 64-cap axis).
  • activeAttestationCountOf(subjectDid): active benign-band count (reclaimable 256-cap axis).
  • attestationsOf(subjectDid): all benign-band attestation ids (append-only, up to 512).
  • adverseAttestationsOf(subjectDid): all adverse-band attestation ids (separate band, up to 128).
  • subjectConsentNonce(subjectDid): DID-scoped benign-consent nonce for building consent typed data.
  • attesterNonce(attester): per-attester nonce mixed into attestationId derivation.

Writes

  • createAttestation(opts): 4-arg direct create; correct for adverse/regulatory writes (no consent). A benign method via this overload reverts MissingSubjectConsent. Decodes { attestationId }.
  • prepareCreateAttestation(opts): benign path; builds the subject EIP-712 consent and returns { typedData, signer, submit } (submit sends the 5-arg createAttestation). Must be called on the attester's client.
  • revokeAttestation(opts): creator-only revoke (msg.sender == attester); axis-aware, terminal.
  • cancelConsent(subjectDid): bump the DID-scoped consent nonce, invalidating not-yet-submitted benign consents; subject-key authed.

Events

  • events.getAttestationCreated(opts): AttestationCreated (both axes); lands verified: false since the event alone does not discriminate the create gate.
  • events.getAdverseAttestationCreated(opts): AdverseAttestationCreated (adverse writes only); verified: true, carries familyPrefixHash.
  • events.getAttestationRevoked(opts): AttestationRevoked; verified: true via the creator-only revoke gate.

EIP-712 typed data

  • buildConsentToAttestationTypedData(domain, message): subject's single-use consent for a benign attestation (ConsentToAttestation).

attesters

Wraps AttesterRegistry (Layer B supporting infrastructure): the operational-attester roster and supported-method registry that underwrites every attestation creation accepted by IdentityAttestations. Attesters are plain addresses; method ids are plain UTF-8 strings. All writes are role-gated (no signature-bearing or permissionless paths). Assembled via createAttestersNamespace(ctx).

Reads

  • isAuthorized(attester, methodId): canonical gate: attester active AND method active AND grant present.
  • isAttesterActive(attester): registered and not suspended.
  • isAttesterSuspended(attester): currently suspended.
  • isMethodRegistered(methodId): method registered and active.
  • isCommonMethod(methodId): flagged common (informational only).
  • getAttester(attester): full attester record; null when never onboarded.
  • getAttesterMethods(attester): methods currently granted to an attester.
  • getMethod(methodId): full method record; null when never registered.
  • attesters(): snapshot of listed attester addresses (includes suspended).
  • attesterCount(): roster count (active + suspended).
  • methods(): all registered methods (common + custom).
  • methodCount(): registered-method count.

Writes

  • addCommonMethod(methodId): register a new common method; requires METHOD_ADMIN_ROLE (timelock).
  • addAttester(attester, supportedMethods): onboard an attester with initial methods; requires ATTESTER_ADMIN_ROLE (timelock).

Events

  • events.getAttesterAdded(opts): AttesterAdded; verified: true via role gate.
  • events.getCommonMethodAdded(opts): reads raw MethodRegistered logs, filters to isCommon === true, returns CommonMethodAdded.
  • events.getAttesterSuspended(opts): AttesterSuspended with reasonHash; verified: true via role gate.

disclosure

Wraps SelectiveDisclosure (Layer B): the user-controlled consent-signal primitive authorizing attestation reads. Every grant signature must recover the subject DID's current controlling key via GuardianRegistry.resolveCurrentKey. Assembled via createDisclosureNamespace(ctx).

Reads

  • getGrant(grantId): single grant record; null when it does not exist.
  • hasActiveGrant(subjectDid, reader, attestationId): returns { found, grantId }.
  • grantsOf(subjectDid): all grant ids (active + revoked + expired) for a subject.
  • isScopeInCatalog(scopeId): scope in the Phase 0 canonical catalog (informational).
  • isRevoked(grantId): O(1) revocation lookup.
  • verifyGrantForRead(grantId, reader, attestationId): core consent gate for source-0 (AttestationsRegistry).
  • verifyGrantForReadWithSource(grantId, reader, attestationId, source): source-aware overload; source 0 or 1 (reverts UnknownSource if higher).
  • nonceOf(signer): EIP-712 nonce shared across record and revoke-by-signature.
  • getMaxGrantsPerSubject(): on-chain MAX_GRANTS_PER_SUBJECT.
  • getMaxGrantExpiryDelta(): on-chain MAX_GRANT_EXPIRY_DELTA.
  • getScopeAllAttestations(): on-chain SCOPE_ALL_ATTESTATIONS sentinel.

Writes

  • prepareRecordGrant(opts): signature-bearing grant; returns { typedData, signer, submit } (submit calls recordGrant).
  • revokeGrant(grantId): direct-caller revoke by the subject's current controlling key.
  • prepareRevokeGrant(opts): signature-based revoke; resolves the current key, returns { typedData, submit } (submit calls revokeGrantBySignature).

Events

  • events.getGrantRecorded(opts): GrantRecorded; verified: true via EIP-712 signature.
  • events.getGrantRevoked(opts): GrantRevoked with revocationPath (1 signature / 2 direct); verified: true.
  • events.getScopeSeeded(opts): ScopeSeeded; verified: true by construction (constructor-only emission).

EIP-712 typed data

  • buildRecordGrantTypedData(domain, message): GrantDisclosure struct for recordGrant.
  • buildRevokeGrantTypedData(domain, message): RevokeGrant struct for revokeGrantBySignature.

schemas

Static, codegen-populated registry of the canonical attestation schemas for Base Sepolia. No contract calls: it is a generated data table consumed by the attestations namespace and tests. Regenerated with pnpm run codegen:schemas.

Exports

  • canonicalSchemas: the generated map of canonical schema entries (keyed by name, e.g. PHONE_VERIFIED, EDUCATED_AT, EMPLOYED_BY), re-exported from generated/base-sepolia.
  • CanonicalSchemaEntry (type): shape of an entry (id, name, abiDefinition, policy of OPEN/ACCREDITED/RESTRICTED, revocable, expires, requiresSubjectConsent, defaultExpiry, maxExpiry, maxAttestationsPerSubject, issuanceFee).

recovery

Wraps GuardianRegistry (guardian-quorum social recovery). Non-upgradeable, non-pausable, role-free. Authorization is by msg.sender against resolveCurrentKey or guardian membership; no EIP-712 signatures, the transaction envelope is the proof of key control. Constructed by createRecoveryNamespace(ctx).

Reads

  • resolveCurrentKey(did): current controlling key for a DID (override map first, else IdentityRegistry).
  • getGuardians(did): guardian set as { guardianDids, threshold, initialized }.
  • getRecovery(recoveryId): full RecoveryRequest struct.
  • activeRecoveryId(did): the one in-flight recovery ID, or zero.
  • hasApproved(recoveryId, guardianDid): whether a guardian has approved a recovery.
  • currentKeyOverride(did): raw override key (zero means fall through to IdentityRegistry).
  • getOverrideSource(did): override provenance (NONE, ABANDONMENT, GUARDIAN).
  • recoveryGeneration(did): monotonic per-DID override generation counter.
  • postVetoCooldownUntil(did): unix timestamp before which no new recovery may start.

Writes

  • setGuardians({ did, guardianDids }): register/replace the guardian set (controller-only); clears in-flight recovery and cooldown.
  • initiateRecovery({ did, newDeviceKey, contextNoteHash }): open a recovery request, 7-day timelock; returns { recoveryId }.
  • approveRecovery({ recoveryId, guardianDid }): guardian approves a recovery.
  • vetoRecovery({ recoveryId, guardianDid }): guardian vetoes; arms a post-veto cooldown when vetoer differs from initiator.
  • finalizeRecovery({ recoveryId }): finalize via M-of-N approvals or expired timelock; installs the new key override.

Events

  • events.getGuardiansSet(opts): GuardiansSet logs (filter by did).
  • events.getRecoveryInitiated(opts): RecoveryInitiated logs (filter by did, recoveryId).
  • events.getRecoveryApproved(opts): RecoveryApproved logs (filter by recoveryId, guardianDid).
  • events.getRecoveryVetoed(opts): RecoveryVetoed logs (filter by recoveryId, guardianDid).
  • events.getRecoveryCompleted(opts): RecoveryCompleted logs, carries via (VIA_APPROVALS or VIA_TIMELOCK).

Constants

  • MIN_GUARDIANS(): minimum guardian-set size (2).
  • MAX_GUARDIANS(): maximum guardian-set size (7).
  • TIMELOCK_DURATION(): recovery timelock (7 days, seconds).
  • TIMELOCK_APPROVAL_FLOOR(): approval floor for the timelock finalization path (2).
  • POST_VETO_COOLDOWN(): post-veto re-initiation cooling-off (7 days, seconds).
  • VIA_APPROVALS(): tag for M-of-N-approvals finalization.
  • VIA_TIMELOCK(): tag for timelock-expiration finalization.

Exported types: RecoveryState (None/Active/Vetoed/Completed), OverrideSource (NONE/ABANDONMENT/GUARDIAN), GuardianSet, RecoveryRequest, plus the five event types.

abandonment

Wraps AbandonmentRegistry, the hostile-builder-recovery primitive layered on GuardianRegistry: a 60-day timelocked abandonment claim, vetoable by the current key or by registered guardians once veto count reaches the M-of-N threshold. Non-upgradeable, role-free. All writes are direct calls, no EIP-712 signatures. Constructed by createAbandonmentNamespace(ctx).

Reads

  • getAbandonment(abandonmentId): full Abandonment record, or null for unknown IDs.
  • activeAbandonmentId(did): currently-active abandonment ID for a DID, or zero.
  • abandonmentEpoch(did): abandonment-finalized counter for a DID.
  • hasVetoed(abandonmentId, vetoerDid): whether a vetoer (or the current-key sentinel when zero) has vetoed.
  • vetoThresholdFor(did): computes { m, n } (M = floor(N/2)+1, floored at VETO_FLOOR).
  • claimTierFor(did): baseline claim-tier preview from institutional-handle signal alone.
  • claimTierForWithProof(did, attestationIds): tier preview with an activity-proof array (fail-closed, monotone-up).

Writes

  • initiateAbandonment({ did, newKey, contextHash, attestationId }): baseline claim; returns { abandonmentId }.
  • initiateAbandonmentWithProof({ did, newKey, contextHash, attestationId, activityAttestationIds }): claim with activity-proof array for High-tier proof-up; returns { abandonmentId }.
  • vetoAbandonment({ abandonmentId, vetoerDid }): veto via current-key sentinel (zero vetoerDid) or guardian DID.
  • finalizeAbandonment({ abandonmentId }): finalize after the 60-day timelock with veto count below threshold; writes the key override.
  • cancelActiveAbandonment(did): current controller cancels its own active claim before finalization.

Events

  • events.getAbandonmentInitiated(opts): AbandonmentInitiated logs (filter by did, newKey).
  • events.getAbandonmentVetoed(opts): AbandonmentVetoed logs (filter by did, vetoerDid).
  • events.getAbandonmentFinalized(opts): AbandonmentFinalized logs (filter by did, newKey).
  • events.getActiveAbandonmentCancelled(opts): ActiveAbandonmentCancelled logs (emitted when a guardian recovery clears a stale claim).
  • events.getPostVetoReInitCooldownSet(opts): PostVetoReInitCooldownSet logs, carries cooldownUntil.

Constants

  • TIMELOCK_DURATION(): 60-day vetoable timelock.
  • VETO_FLOOR(): minimum veto threshold (2), prevents solo-veto.
  • AB_POST_VETO_COOLDOWN(): 7-day post-veto re-initiation cooldown.
  • HIGH_TIER_ATTESTATION_FRESHNESS(): 30-day freshness window for the institutional-tier re-verification attestation.
  • ACTIVITY_PROOF_MAX_IDS(): max entries in the activity-proof array.
  • ACTIVITY_ATTESTATION_COUNT_THRESHOLD(): attestation-count threshold for the High-tier signal.
  • ACTIVITY_ATTESTATION_LOOKBACK(): attestation lookback window (seconds).
  • ACTIVITY_MIN_DISTINCT_ISSUERS(): minimum distinct accredited issuers (K).
  • ACTIVITY_MIN_DID_AGE(): DID-age corroborator floor (seconds).

Exported types: AbandonmentTier (Low/High), Abandonment, plus the five event types.

delegation

Wraps DelegationRegistry (N6), the delegated-authority seam: a DID controller signs a scoped, capped, expiring grant to a delegate, and the delegate signs per-action authorizations that consumer contracts (PaymentsRouter, SavingsRegistry, GroupSavings, AgentSettlement) verify and consume. Constructed by createDelegationNamespace(ctx). Grant/SetCap are controller-signed; Action is delegate-signed; revoke is a direct controller-only call.

Reads

  • getGrant(did, delegate): the grant a DID issued to a delegate, or null.
  • getCap(did, delegate, token): per-token cap with rolling daily accumulator.
  • canAuthorize(req): preview whether an action request would authorize (scope + cap + liveness) without consuming.
  • grantNonce(did): per-DID controller-signed grant/setCap nonce.
  • actionNonce(did, delegate): per-(did,delegate) delegate-signed action nonce.
  • currentControllerGen(did): DID's current controller-generation stamp.
  • guardianRegistry(): wired GuardianRegistry address (controller-key resolution).
  • identityRegistry(): wired IdentityRegistry address (DID liveness).
  • revocationRegistry(): wired RevocationRegistry address (revocation liveness).
  • abandonmentRegistry(): wired AbandonmentRegistry address (recovery-override oracle).

Writes

  • createGrant({ params, signature }): create/widen a grant from a controller-signed Grant permit.
  • prepareCreateGrant({ did, delegate, scopeBitmap, expiry, token, perTxCap, dailyCap, deadline }): reads the grant nonce, resolves the controller signer; returns { typedData, signer, submit }.
  • setCap({ params, signature }): set/update an additional-token cap from a controller-signed SetCap permit.
  • prepareSetCap({ did, delegate, token, perTxCap, dailyCap, deadline }): returns { typedData, signer, submit }.
  • revoke(did, delegate): instantly revoke a delegate's grant (controller-only, no signature).
  • authorizeAndConsume({ req, signature }): verify and consume a delegate-signed action (low-level consume primitive).
  • prepareAuthorizeAndConsume({ did, delegate, action, token, amount, deadline }): reads the action nonce; returns { typedData, signer, submit }.

Events

  • events.getGrantCreated(opts): GrantCreated logs (filter by did, delegate).
  • events.getGrantRevoked(opts): GrantRevoked logs (filter by did, delegate).
  • events.getCapSet(opts): CapSet logs (filter by did, delegate, token).
  • events.getDelegatedActionConsumed(opts): DelegatedActionConsumed logs (nonce burned + value authorized).

EIP-712 typed data

  • buildDelegationGrantTypedData(domain, message): controller-signed Grant permit builder.
  • buildDelegationSetCapTypedData(domain, message): controller-signed SetCap permit builder.
  • buildDelegationActionTypedData(domain, message): delegate-signed Action permit builder (verified against the DelegationRegistry domain).

Constants

  • DelegationAction: action scope bits, PAYMENT (PaymentsRouter), AGENT_CASH_OUT (AgentSettlement), SAVINGS_DEPOSIT (SavingsRegistry), GROUP_CONTRIB (GroupSavings).

Exported types: Grant, Cap, GrantParams, CapParams, DelegationActionRequest, plus the four event types.

vouching

Wraps VouchingRegistry (Layer 2 organic trust): symmetric vouch and revocation records between DIDs, generic at the protocol layer for consumers to interpret per use case. Constructed by createVouchingNamespace(ctx). Direct writes need no signature; the prepare* writes are EIP-712 signature-bearing.

Reads

  • getVouch(voucherDid, vouchedDid): the { vouch, revocation } entries for a pair.
  • isVouchActive(voucherDid, vouchedDid): vouch exists and is not revoked.
  • isVoucherCurrent(voucherDid, vouchedDid): active and the voucher's current key still matches the signing key (fresh-vouch check).
  • vouchedFor(vouchedDid): append-only array of vouchers for a subject.
  • vouchesOfPaged(vouchedDid, offset, limit): paginated variant returning { page, total }.
  • vouchesBy(voucherDid): append-only array of subjects a voucher has vouched for.
  • activeVoucherCount(vouchedDid): O(1) count of active (non-revoked) vouchers.
  • nonceOf(signer): EIP-712 nonce for a signer key.
  • isRevokeEligible(vouchedDid, voucherDid): whether a voucher is enrolled for revoke-quorum eligibility.
  • getMaxVouchesPerVouched(): hard cap on active vouchers per subject (256).
  • getMaxVouchesPerVouchedTotal(): hard cap on total (active + revoked) vouchers per subject (512).

Writes

  • vouch(voucherDid, vouchedDid): direct vouch (caller must be the voucher's current key).
  • prepareVouch({ voucherDid, vouchedDid, deadline, currentKey }): reads the nonce, returns { typedData, signer, submit }; submit lands vouchBySignature.
  • revokeVouch(voucherDid, vouchedDid): direct vouch revocation (voucher's current key).
  • prepareRevokeVouch({ voucherDid, vouchedDid, deadline, currentKey }): returns { typedData, signer, submit }; submit lands revokeVouchBySignature.
  • setRevokeEligibility(vouchedDid, voucherDid, eligible): subject's controller enrolls/disenrolls a voucher for revoke-quorum eligibility.

Events

  • events.getVouchRecorded(opts): VouchRecorded logs (filter by voucherDid, vouchedDid).
  • events.getVouchRevoked(opts): VouchRevoked logs (filter by voucherDid, vouchedDid).
  • events.getRevokeEligibilitySet(opts): RevokeEligibilitySet logs, carries eligible.

EIP-712 typed data

  • buildVouchTypedData(domain, message): Vouch permit builder.
  • buildRevokeVouchTypedData(domain, message): RevokeVouch permit builder.

Exported types: VouchEntry, RevocationEntry, plus the three event types.

reputation

Wraps ReputationExport (Layer B, read-only). Assembles a portable ReputationBundle from AttestationsRegistry (source 0) and IdentityAttestations (source 1), gated by SelectiveDisclosure consent and subject liveness (IdentityRegistry / RevocationRegistry). Every function is view: no writes, no events, no persistence.

Reads

  • exportBundle({ subjectDid, reader, attestationIds, identityAttestationIds, grantIds }): assemble a bundle from explicit item-id lists plus consent grant ids; failed-consent items are omitted and counted in omittedCount (SKIP mode); subject-DID mismatch reverts.
  • exportBundleByScope({ subjectDid, reader, scopeRoot, grantId }): assemble a bundle by a single method-prefix / scope-root grant (shape-1 + shape-3; a shape-2 method grant does not cover source 1).
  • verifyBundleItem({ subjectDid, reader, attestationId, grantId, source }): verify one item (consent + source-validity + freshness) without assembling a bundle.
  • isItemExportable({ subjectDid, reader, attestationId, grantId, source }): true iff the item would be included (consented + source-valid).
  • freshnessOf(attestationId, source): live freshness derivation for one attestation.
  • subjectLiveness(subjectDid): returns { live, revoked }.
  • attestationsRegistry(): wired source-0 registry address.
  • identityAttestations(): wired source-1 registry address.
  • identityRegistry(): wired subject-liveness registry address.
  • revocationRegistry(): wired subject/key revocation registry address.
  • selectiveDisclosure(): wired consent-gate address.

Constants

  • BUNDLE_FORMAT_VERSION(): bundle wire-format version.
  • DEFAULT_STALE_AFTER(): advisory staleness window (180 days; not a rejection).
  • MAX_BUNDLE_ITEMS(): max items per bundle (reverts BundleTooLarge before iteration).

Exported types / enums: AttestationSource (ATTESTATIONS_REGISTRY=0, IDENTITY_ATTESTATIONS=1), FreshnessVerdict (FRESH, EXPIRED, REVOKED, NON_EXPIRING, INVALID), FreshnessRecord, GrantProof, BundleItem, ReputationBundle, SubjectLiveness.

agentReputation

Wraps AgentReputation: a portable per-agent service-reputation record (settlement / dispute / slash counts, tier). Read-only from the SDK: the mutating surface (recordSettlement / recordDispute / recordSlash) is written contract-to-contract by the N1 settlement writers, never by an SDK consumer, so this namespace exposes reads and the record events but no write methods.

Reads

  • serviceStatsOf(agentId): accumulated ServiceStats (all zero in Phase 1, writer unwired).
  • tierOf(agentId): certification tier derived from stats plus ACA cert attestation.
  • isCertified(agentId): true iff the agent holds a valid ACA certification attestation.
  • acaCertSchemaId(): schema id used for ACA certification attestations.
  • agentRegistry(): wired agent identity/liveness registry address.
  • attestationsRegistry(): wired ACA-cert source address.

Events

  • events.getSettlementRecorded({ fromBlock?, toBlock?, agentId? }): settlement recorded (bumps count + cumulative volume).
  • events.getDisputeRecorded({ fromBlock?, toBlock?, agentId? }): dispute recorded against an agent.
  • events.getSlashRecorded({ fromBlock?, toBlock?, agentId? }): slash recorded against an agent.

Constants

  • RATE_MIN_SETTLEMENTS(): minimum settlements before a settlement/dispute rate is computed.
  • DISPUTE_RATE_DEGRADE_BPS(): dispute-rate degradation per dispute (bps).
  • PREMIUM_MIN_SETTLEMENTS(): minimum settlements for PREMIUM tier.
  • PREMIUM_TENURE(): minimum tenure (seconds) for PREMIUM tier.

Exported types / enums: AcaTier (NONE=0, PROVISIONAL=1, CERTIFIED=2, PREMIUM=3), ServiceStats, SettlementRecordedEvent, DisputeRecordedEvent, SlashRecordedEvent.

complaints

Wraps ComplaintRegistry: user-filed complaints against agents, tied to a specific settlement, with a cooling-off window and a false-report strike system. Abusive complainers accrue strikes and are suspended at the ceiling. No EIP-712 signatures; no pause. fileComplaint is the permissionless user path; flagFalseReport is COMPLAINT_REVIEWER_ROLE.

Reads

  • lastFiledAt(complainerDid, agentId): timestamp the complainer last filed against this agent (cooling-off basis), 0 if never.
  • falseReportStrikes(complainerDid): false-report strikes accrued.
  • validatedComplaints(complainerDid): complaints later validated (not false).
  • isComplainerSuspended(complainerDid): true iff struck out at MAX_FALSE_REPORT_STRIKES.
  • agentReputation(): wired dispute-recorder target address.
  • n1(): wired N1 settlement contract (settlement-existence oracle) address.

Writes

  • fileComplaint({ complainerDid, agentId, settlementId }): file a complaint for a specific settlement; caller must control the DID, the settlement must exist (N1 oracle), and the cooling-off window must have elapsed; records a dispute on AgentReputation. Returns a TxBuilder.
  • flagFalseReport({ complainerDid, reasonHash }): mark a report false (COMPLAINT_REVIEWER_ROLE); increments strikes, suspends at the ceiling. Returns a TxBuilder.

Events

  • events.getComplaintFiled({ fromBlock?, toBlock?, complainerDid?, agentId?, settlementId? }): a complaint was filed.
  • events.getFalseReportFlagged({ fromBlock?, toBlock?, complainerDid? }): a report was flagged false (strike recorded).

Constants

  • COOLING_OFF(): cooling-off window between complaints against the same agent (seconds).
  • MAX_FALSE_REPORT_STRIKES(): strikes before a complainer is suspended.

Exported types: ComplaintFiledEvent, FalseReportFlaggedEvent.

payments

Wraps PaymentsRouter (Layer A settlement). Whitelisted-token transfers with a protocol fee forwarded to Treasury, an optional attestation-gated recipient check, atomic single-token batches, and the permissionless fee-increase timelock trigger. All writes are direct-caller and require a prior ERC-20 allowance to the router; the SDK does not auto-approve. Routing is dormant in Phase 0 (arms via the 14-day timelock).

Reads

  • quoteFee(amount): contract fee + net for a hypothetical transfer, returns { fee, net }.
  • nonceOf(sender): per-sender transfer nonce used for transferId derivation (not an EIP-712 nonce).
  • volumeOf(sender): lifetime cumulative outgoing volume, summed across whitelisted tokens.
  • isTokenWhitelisted(token): whether a token is on the whitelist.
  • feeParameters(): current fee params as { bps, minFee, cap }.
  • pendingFeeIncrease(): queued fee increase or null when none.
  • paused(): whether user-facing transfers are paused.

Writes

  • transfer(opts): single transfer; decodes to { transferId, fee, net }. Requires ERC-20 allowance.
  • transferWithAttestation(opts): transfer gated by the recipient DID holding a valid attestation under a schema; preflights hasValidAttestation.
  • batchTransfer(opts): atomic, all-or-nothing single-token batch (cap MAX_BATCH_SIZE = 50); decodes to { transferIds }.
  • executeFeeIncrease(): permissionless trigger to apply a queued fee increase after its 14-day timelock elapses.

Events

  • events.getTokenTransferred(opts): marquee event; caller-supplied DID fields land verified: false with a lazy verifyDidOwnership() resolver.
  • events.getAttestationGatedTransferAccepted(opts): sibling of a gated transfer; exposes a lazy resolveAttestationProof() snapshot resolver.
  • events.getBatchTransferred(opts): batch summary (count, totalAmount, totalFee).
  • events.getFeeParametersChanged(opts): fee-parameter transitions.
  • events.getFeeIncreaseProposed(opts): a fee increase was queued.
  • events.getFeeIncreaseCancelled(opts): a queued fee increase was cancelled.

EIP-712 typed data

  • None. The PaymentsRouter contract has no typed-data structs; all writes are direct-caller.

Constants

  • computeFee(amount, params): pure client-side mirror of the contract fee math, returns { fee, net }.
  • MAX_FEE_BPS = 100 (1.00% ceiling on feeBps).
  • MAX_MIN_FEE = 1_000_000n (minFee upper bound).
  • MAX_FEE_CAP = 50_000_000n (feeCap upper bound).
  • FEE_INCREASE_TIMELOCK_SECONDS = 14 days.
  • MAX_BATCH_SIZE = 50 (atomic batch cap).
  • REQUIRED_TOKEN_DECIMALS = 6 (Phase 0 whitelist-decimals invariant).
  • BPS_DENOMINATOR = 10_000n.
  • canonicalTokens / CanonicalTokenEntry: codegen token registry entry (address, symbol, decimals, displayName, source).

treasury

Wraps Treasury (Layer A settlement). Passive receiver of protocol fees and slash proceeds; holds no cross-namespace dependencies. Reads-only in the SDK: balances and pause status. Withdrawals and pause are governance-scoped writes (WITHDRAWER_ROLE on the 14-day TimelockController; PAUSER on the Foundation multisig) and are not wrapped here.

Reads

  • ethBalance(): native ETH balance held by Treasury (wei).
  • tokenBalance(token): ERC-20 balance for one token in native decimals.
  • tokenBalances(tokens): parallel-batched per-token balances, returns a Map keyed by token address.
  • paused(): whether withdrawals are paused (inflows are never blocked).

Events

  • events.getWithdrawnETH(opts): ETH withdrawals (recipient, amount, category, reasonHash); role-gated, verified: true.
  • events.getWithdrawnERC20(opts): ERC-20 withdrawals (token, recipient, amount, category, reasonHash); role-gated, verified: true.

EIP-712 typed data

  • None. The Treasury contract has no typed-data structs. No deposit events are emitted by design; inflows are read from source-contract events.

Constants

  • WITHDRAWAL_TIMELOCK_SECONDS: alias of the canonical 14-day timelock delay (enforced by the TimelockController, surfaced as a wallet-display value).

rates

Wraps RateOracle (Layer A). A hybrid push/pull exchange-rate substrate for currency pairs: canonical rates pushed by Foundation signers, plus a stateless pull verifier for consumers carrying fresh signed attestations. Pairs are keyed by a plain bytes32 pairId derived via computePairId. Rate signing is dormant in Phase 0 (signer registration and pair seeding are future governance actions).

Reads

  • getRate(pairId): full canonical rate record; check .registered and hasFreshRate before trusting .rate.
  • hasFreshRate(pairId): whether the pair has a rate fresh under its tier tolerance (fixed pegs always fresh).
  • isFresh(pairId): diagnostic { fresh, ageSeconds, ageBlocks }; ages saturate for unregistered/never-attested pairs.
  • freshness(tier): per-tier tolerance { maxBlockAge, maxTimestampAge }.
  • registeredPairs(): enumeration of all registered pair IDs.
  • computePairId(base, quote): pure helper deriving the canonical pairId (keccak256(base + "/" + quote)).
  • verifyAttestation(attestation, signatures, maxBlockAge?): stateless pull-path view verification; optional caller-supplied block-age window may tighten (never loosen) the tier default.
  • signerRegistry(): the SignerRegistry pointer consulted on every attestation.
  • observationSkewSeconds(): max permitted clock drift between a signer observation and chain time.
  • paused(): whether the push path (attestRate) is paused; reads stay available.

Writes

  • attestRate(opts): permissionless push of a signed rate attestation; the threshold signatures are the authority, msg.sender is irrelevant.
  • addPair(opts): register a new pair (RATE_ADMIN_ROLE / timelock).
  • removePair(pairId): remove a registered pair (RATE_ADMIN_ROLE / timelock).
  • setFixedPeg(opts): update the rate of a Tier.Fixed peg pair (RATE_ADMIN_ROLE / timelock).
  • setTierFreshness(opts): adjust freshness tolerance for a variable tier (RATE_ADMIN_ROLE / timelock).
  • setObservationSkewSeconds(newSkew): set the max observation clock-drift window (RATE_ADMIN_ROLE / timelock).
  • pause() / unpause(): pause or resume the push path (PAUSER_ROLE / Foundation multisig).

Events

  • events.getRateAttested(opts): rate pushes; authenticated by the threshold-signature gate, verified: true. Filterable by indexed pairId.
  • events.getPairAdded(opts): pair registrations; authenticated by RATE_ADMIN_ROLE (or the initializer), verified: true.

EIP-712 typed data

  • No SDK prepare* split. Attestation signatures are produced off-chain by the registered signer set over the EIP-712 digest, not by the transaction sender's wallet, so there is no wallet-signing step to prepare.

Constants

  • Tier: pair cadence/freshness enum, Fixed (0), Daily (1), Hourly (2). Also exported: types RateEntry, FreshnessTolerance, FreshnessStatus, RateAttestation, VerifiedAttestation.

signers

Wraps SignerRegistry (Layer A supporting infrastructure). The multisig-pattern signer-authorization primitive underwriting every RateOracle push attestation and pull verification: it stores the global authorized signer set and threshold, with no rate opinions and no funds custody. All writes are SIGNER_ADMIN_ROLE and timelock-gated. Per-pair reads accept a pairId that is ignored in v1 but kept for forward compatibility.

Reads

  • isAuthorized(signer): whether a signer is in the authorized set (unscoped v1 read).
  • isAuthorizedFor(signer, pairId): v2-forward-compatible authorization check (pairId ignored in v1).
  • threshold(): global minimum distinct signatures for a valid attestation.
  • thresholdFor(pairId): v2-forward-compatible threshold read (pairId ignored in v1).
  • signers(): snapshot of the currently authorized signer set.
  • signerCount(): size of the authorized signer set.

Writes

  • addSigner(signer): authorize a new rate signer (SIGNER_ADMIN_ROLE / timelock).
  • removeSigner(signer): remove a signer; reverts if it would drop below threshold (SIGNER_ADMIN_ROLE / timelock).
  • setThreshold(newThreshold): update the global threshold (SIGNER_ADMIN_ROLE / timelock).

Events

  • events.getSignerAdded(opts): signer added; verified: true. Filterable by indexed signer.
  • events.getSignerRemoved(opts): signer removed; verified: true. Filterable by indexed signer.
  • events.getThresholdSet(opts): threshold changed (including the seeding event with oldThreshold == 0); non-indexed fields.

EIP-712 typed data

  • None. No signature-bearing or direct-caller writes; every mutating call is role-gated through the timelock.

protocolConfig

Wraps ProtocolConfig (Layer A). The Foundation-governed token-whitelist and per-token economic-config contract. This is a reads-only SDK namespace: apps read the whitelist and per-token config; the token-lifecycle writes (addToken, setTokenConfig, removeToken, pauseToken, setMaxSwapSpreadBps) are timelock/PAUSER governance and are not wrapped. The 5-token whitelist (USDC, USDT, EURC, cbBTC, WETH) is live in Phase 0.

Reads

  • isWhitelisted(token): whether a token is whitelisted and active.
  • getTokenConfig(token): full per-token config record (TokenConfig).
  • listWhitelistedTokens(): all whitelisted token addresses.
  • whitelistedTokenCount(): count of whitelisted tokens.
  • tokenIndex(token): 1-based whitelist index (0 = not present).
  • maxSwapSpreadBps(): current max swap spread (bps).
  • maxFeeCapByDecimals(decimals): fee-cap ceiling for a token-decimals bracket (native units).
  • maxMinFeeByDecimals(decimals): min-fee ceiling for a token-decimals bracket (native units).
  • DEFAULT_MAX_SWAP_SPREAD_BPS(): contract default max swap spread (bps).
  • MAX_SWAP_SPREAD_BPS_CEILING(): hard ceiling on the configurable max swap spread (bps).
  • MAX_SYMBOL_LEN(): max token-symbol length.

Events

  • events.getTokenAdded(opts): token added to the whitelist; filterable by indexed token and addedBy.
  • events.getTokenRemoved(opts): token removed; filterable by indexed token and removedBy.
  • events.getTokenConfigUpdated(opts): per-token fee/active config updated; filterable by token and changedBy.
  • events.getTokenPaused(opts): surgical PAUSER pause of a token; filterable by token and pauser.
  • events.getTokenUnpaused(opts): token unpaused; filterable by token and unpauser.
  • events.getMaxSwapSpreadBpsSet(opts): max-swap-spread updated; filterable by setBy.

EIP-712 typed data

  • None. No signature paths; the token-lifecycle writes are timelock/PAUSER governance and are not wrapped in this namespace.

Constants

  • Exported type TokenConfig (tokenAddress, decimals, minFee, feeCap, symbol, addedAt, active). No module-level constant exports; the three ceiling constants above are read from the contract.

timelock

Wraps the OpenZeppelin TimelockController, the governance gatekeeper that holds UPGRADER_ROLE on every registry and WITHDRAWER_ROLE on Treasury, so every upgrade and every Foundation fee-spend passes through the 14-day delay. In the SDK it is a read-only transparency surface: check whether a governance operation is pending, ready, or done, read the minimum delay, and query role membership. The state-changing operations (schedule, execute, cancel, updateDelay) are Foundation governance actions enforced on-chain by role, not exposed as SDK calls (deferred to a later batch); there is no EIP-712. Reads are top-level on the namespace (adunai.timelock.getMinDelay()); events live under .events.

Reads

  • getMinDelay(): minimum seconds before an operation is valid (Phase 0 = 1,209,600 = 14 days).
  • getTimestamp(id): when an operation becomes ready; 0n = Unset, 1n = Done, otherwise the Unix ready-time.
  • getOperationState(id): returns OperationState, one of Unset(0), Waiting(1), Ready(2), Done(3).
  • isOperation(id): scheduled (state is not Unset).
  • isOperationPending(id): Waiting or Ready (still pending execution).
  • isOperationReady(id): Ready (delay elapsed, awaiting execute).
  • isOperationDone(id): executed successfully.
  • hasRole(role, account): whether account holds role (for example, can this address propose).
  • getRoleAdmin(role): the admin role that controls grants and revokes of role.
  • getOperationStates(ids[]): parallel-batched multi-id read (N eth_calls; not cached).

Events

  • events.getCallScheduled(opts?): operations scheduled (PROPOSER-gated).
  • events.getCallExecuted(opts?): operations executed.
  • events.getCallSalt(opts?): sparse; emitted only when the salt is non-zero, so treat absence as salt: 0x0…0.
  • events.getCancelled(opts?): cancellations (CANCELLER-gated); the only on-chain record of a cancel.
  • events.getMinDelayChange(opts?): delay-change history (constructor plus updateDelay).
  • events.getRoleAdminChanged(opts?), events.getRoleGranted(opts?), events.getRoleRevoked(opts?): AccessControl role history (replay Granted minus Revoked to reconstruct current members; there is no on-chain enumeration).

Constants

  • PROPOSER_ROLE = 0xb09aa5aeb3702cfd50b6b62bc4532604938f21248a27a1d5ca736082b6819cc1.
  • EXECUTOR_ROLE = 0xd8aa0f3194971a2a116679f7c2090f6939c8d4e01a2a8d7e41d55e5351469e63.
  • CANCELLER_ROLE = 0xfd643c72710c63c0180259aba6b2d05451e3591a24e58b62239378085726f783.
  • DEFAULT_ADMIN_ROLE = 0x0000000000000000000000000000000000000000000000000000000000000000 (bytes32 zero).
  • TIMELOCK_DELAY_SECONDS = 14n * 86400n (1,209,600). Canonical; Treasury re-exports it as WITHDRAWAL_TIMELOCK_SECONDS.

Types exported: TimelockOperationId (branded Hex32) with static .derive({...}) and .deriveBatch({...}) helpers that mirror the contract's hashOperation and hashOperationBatch pure views.

Phase 0 note: on testnet the deployer holds all roles (placeholder). At mainnet the Foundation multisig holds PROPOSER and CANCELLER, and EXECUTOR opens to address(0); the SDK surface is unchanged by that rotation.

savings

Wraps the SavingsRegistry contract: the individual time-locked / goal-savings primitive. A single-user state machine (deposit, lock N days, withdraw at maturity; early-withdraw with penalty routed to Treasury) plus a beneficiary-on-death lifecycle that composes AbandonmentRegistry as the legitimacy oracle. No yield or interest at the protocol layer; protocolFeeBps ships governed-but-dormant.

Reads

  • getDeposit(depositId): full decoded deposit record, or null for an unknown id.
  • getBeneficiary(depositId): beneficiary-on-death record, or null when none designated.
  • getDepositStatus(depositId): deposit status enum.
  • getDepositsByDid(did): all deposit ids owned by a DID (open plus closed).
  • depositCount(did): total deposits ever opened by a DID.
  • openDepositCount(did): currently-open (non-withdrawn) deposit count.
  • isMatured(depositId): true once the deposit reaches its pause-adjusted maturity.
  • timeUntilMaturity(depositId): seconds remaining until maturity (0 if matured).
  • isBeneficiaryClaimEligible(depositId): true if a designated beneficiary may currently claim.
  • earlyWithdrawQuote(depositId): preview gross, penalty, and net for an early withdrawal.
  • getAccruedFee(token): accrued protocol fee for a token (dormant in Phase 0).
  • getProtocolFeeBps(): current protocol fee in bps.
  • getEarlyWithdrawPenaltyBps(): current early-withdraw penalty in bps.
  • paused(): whether deposits/withdrawals are paused.
  • pendingPenaltyBps(): pending early-withdraw penalty awaiting the timelock (0 if none).
  • pendingPenaltyMaturesAt(): when the pending penalty increase matures.
  • pendingProtocolFeeBps(): pending protocol fee awaiting the timelock (0 if none).
  • pendingProtocolFeeMaturesAt(): when the pending protocol-fee increase matures.
  • treasury(): Treasury address (penalty/fee residue sink).
  • protocolConfig(): ProtocolConfig address (token whitelist).
  • identityRegistry(): IdentityRegistry address (DID liveness).
  • revocationRegistry(): RevocationRegistry address.
  • guardianRegistry(): GuardianRegistry address (effective-key resolution).
  • abandonmentRegistry(): AbandonmentRegistry address (beneficiary-claim legitimacy oracle).
  • delegationRegistry(): DelegationRegistry address (delegate-deposit permit verifier).

Writes

  • deposit(params): open a time-locked deposit; TxBuilder decodes to { depositId }.
  • depositByDelegate(opts): open a deposit via a pre-signed DelegationRegistry ActionRequest; decodes to { depositId }.
  • prepareDepositByDelegate(opts): async; builds the delegate permit (reads action nonce, sets SAVINGS_DEPOSIT), returns { typedData, signer, submit }.
  • withdraw(depositId): withdraw a matured deposit in full, no penalty.
  • claimEarlyWithdraw(depositId): withdraw before maturity; penalty routes to Treasury.
  • designateBeneficiary(opts): designate a beneficiary DID (depositor only).
  • clearBeneficiary(depositId): remove the designated beneficiary.
  • relinquishBeneficiary(depositId): begin the depositor's 14-day beneficiary-relinquish escape valve.
  • initiateBeneficiaryClaim(depositId): beneficiary begins a claim (arms the contest window).
  • contestBeneficiaryClaim(depositId): depositor contests/cancels an in-progress claim.
  • claimByBeneficiary(depositId): beneficiary finalizes the claim once eligible (full amount, no penalty).
  • proposeProtocolFeeIncrease(newBps): arm the 14-day timelock for a protocol-fee increase (FEE_ADMIN).
  • executeProtocolFeeIncrease(): execute a matured protocol-fee increase.
  • cancelProtocolFeeIncrease(): cancel a pending protocol-fee increase.
  • setProtocolFeeBps(newBps): set the protocol fee directly (decrease / no-timelock path).
  • proposeEarlyWithdrawPenaltyIncrease(newBps): arm the timelock for a penalty increase.
  • executeEarlyWithdrawPenaltyIncrease(): execute a matured penalty increase.
  • cancelEarlyWithdrawPenaltyIncrease(): cancel a pending penalty increase.
  • setEarlyWithdrawPenaltyBps(newBps): set the penalty directly (decrease / no-timelock path).
  • withdrawFees(token): sweep accrued fees for a token; decodes to { amount }.
  • pause(): pause deposits/withdrawals (PAUSER).
  • unpause(): unpause (PAUSER).

Events

  • getDeposited(opts): deposit opened (filters: depositorDid, depositToken).
  • getWithdrawn(opts): deposit withdrawn (matured or early-with-penalty).
  • getBeneficiaryDesignated(opts): beneficiary designated (filter: beneficiaryDid).
  • getBeneficiaryCleared(opts): beneficiary cleared.
  • getBeneficiaryClaimInitiated(opts): beneficiary began a claim (filter: beneficiaryDid).
  • getBeneficiaryClaimContested(opts): depositor contested a claim (filter: depositorDid).
  • getBeneficiaryRelinquishInitiated(opts): depositor began relinquishing (filter: depositorDid).
  • getBeneficiaryClaimed(opts): claim finalized (filters: depositorDid, beneficiaryDid).
  • getFeesWithdrawn(opts): accrued fees swept (filters: token, to).

EIP-712 typed data

  • buildDelegationActionTypedData: re-exported DelegationRegistry ActionRequest builder used by the delegate-deposit permit.
  • DelegationAction: re-exported action-discriminant enum (delegate deposit uses SAVINGS_DEPOSIT).

Constants

  • MAX_DEPOSITS_PER_DID(): max concurrent deposits per DID.
  • MAX_EARLY_WITHDRAW_PENALTY_BPS(): ceiling on the early-withdraw penalty (bps).
  • MAX_PROTOCOL_FEE_BPS(): ceiling on the protocol fee (bps).
  • MIN_LOCK_DURATION(): minimum lock duration (seconds).
  • MAX_LOCK_DURATION(): maximum lock duration (seconds).
  • MAX_PAUSE_DURATION(): maximum single pause duration (seconds).
  • FEE_INCREASE_TIMELOCK(): fee-increase timelock (14 days).
  • BENEFICIARY_CLAIM_CONTEST_TIMELOCK(): beneficiary-claim contest window (depositor veto).
  • BENEFICIARY_RELINQUISH_TIMELOCK(): beneficiary-relinquish escape-valve timelock.
  • SAVINGS_REGISTRY_DOMAIN_V1(): namespace tag for delegate-action domain scoping.

Also exports the DepositStatus enum (ACTIVE, MATURED, WITHDRAWN, ABANDONED_PENDING, ABANDONED_CLAIMED) and the DepositParams, Deposit, Beneficiary, and EarlyWithdrawQuote types.

groupSavings

Wraps the GroupSavings contract: the Layer A custodial, rotating-payout group-savings primitive (the on-chain esusu / tontine / stokvel). Members contribute each cycle; one member receives the pooled payout per cycle in rotation order. Covers the full group, cycle, membership, default, exit, escrow, and dissolution lifecycle.

Reads

  • getGroup(groupId): full decoded group record, or null for an unknown id.
  • getGroupConfig(groupId): group configuration (immutable after createGroup).
  • getGroupStatus(groupId): group lifecycle status.
  • getCurrentCycle(groupId): the current in-progress cycle.
  • getCycle(groupId, cycleIndex): a specific cycle by index.
  • getCurrentRecipient(groupId): the DID scheduled to receive the current cycle's payout.
  • getMember(groupId, memberDid): full decoded member record, or null if not a member.
  • getMemberStatus(groupId, memberDid): member lifecycle status.
  • listMembers(groupId): all member DIDs in the group.
  • getRotationOrder(groupId): the computed rotation (payout) order.
  • isGroupMember(groupId, memberDid): whether a DID is a member.
  • hasContributedThisCycle(groupId, memberDid): whether a member contributed to the current cycle.
  • memberCount(groupId): live member count.
  • memberContributedToDate(groupId, memberDid): cumulative contributions to date.
  • memberStakeBalance(groupId, memberDid): a member's current stake balance.
  • memberDefaultCount(groupId, memberDid): a member's default count.
  • totalContributed(groupId): total contributed across all cycles.
  • totalPaidOut(groupId): total paid out across all cycles.
  • escrowedRefundOf(token, did): escrowed refund owed to a DID for a token.
  • getAccruedFee(token): accrued protocol fee for a token (dormant in Phase 0).
  • getProtocolFeeBps(): current protocol fee in bps.
  • dissolveQuorumFor(memberCount): dissolve quorum (M) required for a group of N members (pure).
  • paused(): whether contributions/settlement are paused.
  • pendingFeeBps(): pending protocol fee awaiting the timelock (0 if none).
  • pendingFeeMaturesAt(): when the pending fee increase matures.
  • treasury(): Treasury address (terminal residue sink).
  • protocolConfig(): ProtocolConfig address (token whitelist).
  • identityRegistry(): IdentityRegistry address (DID liveness).
  • revocationRegistry(): RevocationRegistry address.
  • guardianRegistry(): GuardianRegistry address (effective-key resolution).
  • identityAttestations(): IdentityAttestations address (membership attestation gate).
  • vouchingRegistry(): VouchingRegistry address (membership vouch gate).
  • abandonmentRegistry(): AbandonmentRegistry address (recovery override oracle).
  • delegationRegistry(): DelegationRegistry address (delegate-contribution permit verifier).

Writes

  • createGroup(config): create a new group (status FORMING); TxBuilder decodes to { groupId }.
  • addMember(groupId, memberDid): add a member to a FORMING group (creator only; attestation/vouch gated).
  • activateGroup(groupId): activate a FORMING group; computes rotation, opens cycle 0.
  • contribute(groupId): contribute the current cycle's amount (caller controls a member DID).
  • contributeByDelegate(opts): contribute for a member via a pre-signed DelegationRegistry ActionRequest.
  • prepareContributeByDelegate(opts): async; builds the delegate permit (reads action nonce, sets GROUP_CONTRIB), returns { typedData, signer, submit }.
  • settleCycle(groupId): settle the current cycle; pay recipient, apply defaults, advance rotation.
  • claimPayout(groupId, cycleIndex): claim a settled cycle's payout (recipient member only).
  • markDefault(groupId, memberDid): mark a member defaulted for the current cycle (permissionless after the due window).
  • voluntaryExit(groupId): voluntarily exit before a payout (refund rules apply).
  • claimEscrow(did, token): claim an escrowed refund; decodes to { amount }.
  • dissolveForming(groupId): dissolve a FORMING group before activation (creator only; pro-rata refunds).
  • proposeDissolve(groupId, reason): propose dissolving an ACTIVE group; arms the M-of-N quorum.
  • approveDissolve(groupId): approve a pending dissolution proposal (member).
  • finalizeDissolve(groupId): finalize dissolution once quorum is met (current-cycle pro-rata refund).
  • proposeProtocolFeeIncrease(newBps): arm the 14-day timelock for a fee increase (FEE_ADMIN).
  • executeProtocolFeeIncrease(): execute a matured fee increase.
  • cancelProtocolFeeIncrease(): cancel a pending fee increase.
  • setProtocolFeeBps(newBps): set the protocol fee directly (decrease / no-timelock path).
  • withdrawFees(token): sweep accrued fees for a token; decodes to { amount }.
  • pause(): pause contributions/settlement (PAUSER).
  • unpause(): unpause (PAUSER).

Events

  • getGroupCreated(opts): new group created (filters: groupId, creatorDid, contributionToken).
  • getMemberAdded(opts): member added to a forming group (filters: groupId, memberDid).
  • getGroupActivated(opts): group activated (filter: groupId).
  • getContributed(opts): a member contributed to a cycle (filters: groupId, memberDid).
  • getCycleSettled(opts): a cycle was settled (filters: groupId, actualRecipient).
  • getPayoutClaimed(opts): a settled payout was claimed (filters: groupId, memberDid).
  • getMemberDefaulted(opts): a member defaulted; applied policy recorded (filters: groupId, memberDid).
  • getMemberExited(opts): a member exited; refund amounts recorded (filters: groupId, memberDid).
  • getGroupCompleted(opts): group completed, all rotations paid out (filter: groupId).
  • getGroupDissolved(opts): group dissolved via member-quorum or forming-cancel (filters: groupId, dissolvedBy).
  • getGroupAutoDissolved(opts): group auto-dissolved on total-cycle default; residue to Treasury (filter: groupId).
  • getEscrowClaimed(opts): an escrowed refund was claimed (filters: memberDid, token).

EIP-712 typed data

  • buildDelegationActionTypedData: re-exported DelegationRegistry ActionRequest builder used by the delegate-contribution permit.
  • DelegationAction: re-exported action-discriminant enum (delegate contribution uses GROUP_CONTRIB).

Constants

  • DISSOLVE_QUORUM_MIN(): absolute minimum dissolve quorum.
  • MIN_GROUP_SIZE(): minimum group size.
  • MAX_GROUP_SIZE(): maximum group size.
  • MIN_CYCLE_DURATION(): minimum cycle duration (seconds).
  • MAX_CYCLE_DURATION(): maximum cycle duration (seconds).
  • MAX_PENALTY_BPS(): ceiling on the default penalty (bps).
  • MAX_PROTOCOL_FEE_BPS(): ceiling on the protocol fee (bps).
  • MAX_PAUSE_DURATION(): maximum single pause duration (seconds).
  • MAX_REQUIRED_ATTESTATIONS(): max required-attestation types in a group config.
  • MAX_SKIP_DEFAULT_BEFORE_REMOVAL(): consecutive skips/defaults before a member is removed.
  • FEE_INCREASE_TIMELOCK(): fee-increase timelock (14 days).

Also exports the lifecycle enums MemberDefaultPolicy (SKIP, PENALTY, FORFEIT), RotationOrdering (FIFO, RANDOMIZED, NEGOTIATED; NEGOTIATED reverts at activation in Phase 0), GroupStatus (NONE, FORMING, ACTIVE, COMPLETED, DISSOLVED), and MemberStatus (NONE, PENDING, ACTIVE, DEFAULTED, EXITED), plus the GroupConfig, Group, Cycle, and Member types.

agents

Wraps AgentRegistry (Layer A settlement plus Layer B identity anchoring): the roster of staked cash-in/cash-out agents, their service areas, sponsored registration, slashing lifecycle, and builder affiliation. All state-mutating writes are direct-caller (the contract enforces isControlledBy per method); one EIP-712 path exists for sponsored (gasless) registration.

Reads

  • resolveAgent(agentId) full agent record, null if never registered
  • agentIdOf(did) agentId bound to a DID, null if none
  • serviceAreasOf(agentId) declared service-area entries
  • serviceAreaCountOf(agentId) count of service areas
  • pendingSlashOf(agentId) queued slash record, null if none
  • agentsInCountry(countryCode) agentIds with a service area in a country
  • isActive(agentId) whether the agent may currently operate
  • minStakeFor(tier) minimum stake for a tier
  • paused() contract pause state
  • affiliationOf(agentId) sponsoring-builder affiliation (operatorId, outstanding, lien maturity)
  • agentConsentNonceOf(agentDid) sponsored-registration consent nonce
  • borrowingBaseInputs(agentId) N4 borrowing-base inputs (stake, outstanding, operatorId, active)
  • effectiveOutstandingOf(agentId) effective outstanding sponsored obligation
  • escrowedSlashProceeds(recipient) escrowed slash proceeds owed to a recipient
  • deriveAgentId(did) on-chain derivation of the agentId for a DID
  • minStakeIndividual() / minStakeBusiness() per-tier minimum stake
  • slashTimelock() slash timelock (seconds)
  • stakeCooldown() stake-withdrawal cooldown (seconds)
  • stakeToken() stake token address
  • treasury() slash-residue sink
  • attestationsRegistry(), builderRegistry(), guardianRegistry(), handleRegistry(), identityRegistry(), revocationRegistry(), n4Pool() wired substrate addresses
  • phoneVerifiedSchemaId() / nationalIdVerifiedSchemaId() personhood-gate schema ids
  • MAX_CONSENT_DEADLINE(), MAX_LIEN_TERM(), SUSPENSION_WITHDRAW_DELAY() on-chain constants

Writes

  • registerAgent(opts) register a new agent, with cross-namespace preflight (identity liveness, PHONE_VERIFIED attestation, institutional-handle checks for BUSINESS tier); decodes to { agentId }
  • increaseStake(opts) top up bonded stake
  • updateFeeSchedule(opts) update fee-schedule hash
  • updateMetadataURI(opts) update metadata-URI hash
  • addServiceArea(opts) / removeServiceArea(opts) manage service areas (remove uses swap-and-pop)
  • deregisterAgent(agentId) begin self-deregistration and start the cooldown
  • withdrawStake(opts) withdraw stake after cooldown, no pending slash
  • executeSlash(agentId) execute a queued slash after timelock (permissionless)
  • registerAgentSponsored(opts) gasless register from an agent-signed consent permit; decodes to { agentId }
  • prepareRegisterAgentSponsored(opts) build the AgentConsent typed data plus signer and a submit helper
  • cancelConsent(agentDid) cancel the agent's pending consent (bumps nonce)
  • proposeSlash(opts) / cancelSlash(agentId) slash proposal lifecycle (role-gated)
  • proposeLendingDefaultSlash(agentId, recordedDebt) / cancelLendingDefaultSlash(agentId) lending-default slash
  • claimSlashEscrow(recipient) claim escrowed slash proceeds
  • suspendAgent(agentId, reasonHash) / reinstateAgent(agentId) suspension governance
  • disaffiliateAgent(agentId) disaffiliate from sponsoring builder
  • setMinStake(tier, minStake), setSlashTimelock(seconds), setStakeCooldown(seconds), setTreasury(treasury) governance setters

Events

  • getAgentRegistered, getStakeIncreased, getFeeScheduleUpdated, getMetadataURIUpdated
  • getServiceAreaAdded, getServiceAreaRemoved, getAgentDeregistered, getStakeWithdrawn
  • getAgentSuspended, getAgentReinstated
  • getSlashProposed, getSlashExecuted, getSlashCancelled
  • getAgentAffiliated, getAgentDisaffiliated, getAgentConsentCancelled, getAffiliationSettled
  • getMinStakeSet, getSlashEscrowClaimed, getSlashProceedsEscrowed
  • getSlashTimelockSet, getStakeCooldownSet, getTreasurySet

EIP-712 typed data

  • buildAgentConsentTypedData(domain, message) agent-signed consent over a sponsored registration; signer is the agent's recovery-aware effective value key

Constants

  • MAX_SERVICE_AREAS (50) per-agent service-area cap
  • MIN_COOLDOWN_SECONDS / MAX_COOLDOWN_SECONDS stake-withdrawal cooldown bounds
  • MIN_SLASH_TIMELOCK_SECONDS / MAX_SLASH_TIMELOCK_SECONDS slash-timelock bounds
  • slashCategoryCapBps(category) per-category slash cap in basis points
  • slashRatio(agent, executedHistory) pure helper: cumulative slashed over current stake
  • disputeCount(history) pure helper: aggregate open/resolved/cancelled slash counts

settlement

Wraps AgentSettlement (N1), the settlement primitive for CASH_IN, CASH_OUT, and own-builder commission legs. Agents call settleCashIn/settleCashOut directly; a gasless alternative routes a user-signed CashLeg through the (unwrapped) forwarder. Includes quote, escrow, and activity reads plus the dispute/interchange admin surface.

Reads

  • quoteCashIn(opts) / quoteCashOut(opts) fee/amount quote for a leg
  • settlementOf(settlementId) append-once settlement record, null if unrecorded
  • settlementNonce(did) per-DID settlement idempotency nonce
  • enrollmentNonce(userDid) per-user cross-builder enrollment nonce
  • escrowedFees(token) escrowed protocol fees for a token
  • escrowedPayout(agentId, token) escrowed agent payout
  • pendingVestedCommission(agentId, token) pending vested deposit commission with unlock time
  • freeTierUsedToday(userDid, token) per-user free-tier cash-out used today
  • velocityUsedToday(agentDid, token) per-agent AML velocity used today
  • distinctCounterpartiesInWindow(agentId, window) distinct counterparties in an activity window
  • qualifyingActivityScore(agentId, window) qualifying-activity score
  • isActivityFlagged(agentId) activity-flag (clawback) signal
  • isSettlementOnHold(settlementId) dispute-hold state
  • resolveKeyExternal(did) override-aware controlling key (the CashLeg signer)
  • resolveValueKeyExternal(did) override-aware value key (payout delivery)
  • paused(), disputeHook(), interchangeSource() state getters
  • agentRegistry(), agentReputation(), builderRegistry(), builderPool(), complianceCompleteness(), travelRule(), settlementConfig(), protocolConfig(), identityRegistry(), guardianRegistry(), revocationRegistry(), abandonmentRegistry(), treasury() wired substrate addresses
  • MAX_CP_PER_BUCKET(), MAX_PAUSE_DURATION() on-chain constants

Writes

  • settleCashIn(opts) / settleCashOut(opts) settle a leg (agent-called); decode to { settlementId }
  • prepareCashLeg(opts) build the user-signed CashLeg typed data plus signer, candidateIdsHash, and nonce (relayer submits via the forwarder)
  • prepareEnrollmentGrant(opts) build the builder-signed EnrollmentGrant typed data plus nonce for the cross-builder branch
  • claimSettlementEscrow(agentId, token) claim an agent's escrowed payout
  • claimFeeEscrow(token) claim escrowed protocol fees to Treasury
  • claimVestedCommission(agentId, token) claim a vested deposit commission
  • setActivityFlag(opts) set/clear an agent activity flag (role-gated)
  • setSettlementHold(opts) set/clear a settlement dispute hold (role-gated)
  • setDisputeHook(hook) set the dispute hook (role-gated)
  • setInterchangeSource(source) set the interchange source (role-gated)

Events

  • getSettlementRecorded, getAgentPayoutEscrowed, getSettlementEscrowClaimed
  • getProtocolFeeEscrowed, getProtocolFeeEscrowClaimed, getProtocolFeeForwarded
  • getDepositCommissionClaimed, getInterchangeLegRequested, getQualifyingActivityCounted
  • getActivityFlagSet, getSettlementHoldSet, getDisputeHookSet, getInterchangeSourceSet

EIP-712 typed data

  • buildEnrollmentGrantTypedData(domain, message) builder-signed cross-builder enrollment consent (verified against the N1 domain)
  • buildCashLegTypedData(domain, message) user-signed settlement leg for the gasless forwarder path (verified against the forwarder domain)

settlementConfig

Wraps N1SettlementConfig, the N1 economic and settlement config (per-token caps, fee curves, and global economics). A reads-only namespace: apps read the config while all setters are CONFIG_ADMIN governance. Exposes reads and config-set events, no writes.

Reads

  • getTokenSettlementConfig(token) per-token settlement caps record
  • tierScheduleOf(token) marginal fee-tier schedule for a token
  • perTxCap(token), dailyCap(token), windowVelocityCap(token) per-token caps
  • travelRuleThreshold(token) travel-rule threshold
  • minFeeOf(token) minimum fee
  • scoreSuppressionCap(token) score-suppression cap
  • perDidDailyFreeAllowanceOf(token) per-DID daily free allowance
  • roundTripWindow(), activityWindow(), maxSettlementSigDeadline() global windows
  • minKycTier() minimum KYC tier for settlement
  • protocolShareBps(), depositRatioBps(), depositCommissionVesting() standardized-split economics
  • BPS_DENOMINATOR(), MAX_KYC_TIER(), MIN_KYC_TIER_FLOOR() on-chain constants

Events

  • getFeeCurveSet, getGlobalEconomicsSet, getMinFeeSet
  • getScoreSuppressionCapSet, getStandardizedSplitSet, getTokenSettlementConfigSet

interchange

Wraps Interchange (N2), the value-less, role-less cross-builder cash-IN quote surface. A reads-only namespace per audit scope: no writes and no domain events.

Reads

  • quoteInterchange(opts) quote a cross-builder cash-IN: { net, commissionD, canCover }
  • builderPool() wired BuilderPool address
  • settlementConfig() wired N1SettlementConfig address

builderPool

Wraps BuilderPool, the per-builder token float (deposit/withdraw) plus the interchange pull and per-DID escrow surface. Direct calls, no signatures.

Reads

  • poolBalanceOf(operatorId, token) total pool balance
  • availableOf(operatorId, token) uncommitted balance
  • committedOf(operatorId, token) committed balance
  • escrowOf(did, token) escrowed interchange owed to a DID
  • canCoverPull(operatorId, token, amount) whether a pull is currently coverable
  • totalToken(token) total held across all builders for a token
  • builderRegistry(), protocolConfig(), revocationRegistry() wired substrate addresses

Writes

  • depositToPool(opts) fund a builder's pool for a token
  • withdrawFromPool(opts) withdraw available balance to a recipient (builder operator)
  • pullInterchange(opts) pull interchange from a payer float to an agent recipient, escrowing to a DID (role-gated)
  • claimEscrow(did, token) claim escrowed interchange; decodes to { amount }

Events

  • getPoolFunded, getPoolWithdrawn
  • getInterchangeEscrowed, getInterchangePulled, getEscrowClaimed

builders

Wraps BuilderRegistry, the roster of admitted builders (VASP-licensed operators that route interchange). Full-wrap of the admit/suspend/reinstate/offboard governance plus the obligation-counter notifier surface; reads for the roster, status, and operator-key resolution. Direct calls, no signatures.

Reads

  • getBuilder(operatorId) full builder record, null if unknown
  • statusOf(operatorId) builder status enum
  • isActiveBuilder(operatorId) whether the operator is ACTIVE
  • builderCount() count of admitted builders
  • listBuilders() all builder operatorIds
  • builderDidOf(operatorId) builder DID behind an operatorId
  • operatorIdOf(builderDid) operatorId for a builder DID
  • operatorKeyOf(operatorId) current operator key address
  • computeOperatorId(builderDid) deterministic operatorId derivation
  • obligationCountOf(operatorId) outstanding-obligation count (blocks offboarding when nonzero)
  • attestationsRegistry(), handleRegistry(), identityRegistry(), guardianRegistry(), revocationRegistry() wired substrate addresses

Writes

  • admitBuilder(opts) admit a builder (role-gated); decodes to { operatorId }
  • suspendBuilder(operatorId, reasonHash) / reinstateBuilder(operatorId) suspension governance
  • offboardBuilder(operatorId) offboard a builder (blocked while obligations outstanding)
  • incrementObligations(operatorId) / decrementObligations(operatorId) obligation-counter notifier surface (contract-to-contract role)

Events

  • getBuilderAdmitted, getBuilderSuspended, getBuilderReinstated, getBuilderOffboarded
  • getObligationIncremented, getObligationDecremented

swaps

Wraps AgentSwapEscrow (N5), agent-to-agent cash/digital swaps with escrow, receiver attestation, and dispute plus timeout resolution. Full-wrap of the swap lifecycle (propose, accept, receiverAttest, confirmRelease, with cancel/expiry/timeout/dispute paths), escrow claim, and governance param setters. Direct calls, no signatures.

Reads

  • resolveSwap(swapId) full swap record, null if unknown
  • quote(swapId) swap split: { releasedToReceiver, spreadKept }
  • escrowedSwapProceeds(did, token) escrowed swap proceeds owed to a DID
  • paused() contract pause state
  • disputeResolveWindow(), minSwapTier(), proposalTtl(), swapTimeout() governance parameters
  • agentRegistry(), agentReputation(), guardianRegistry(), protocolConfig(), revocationRegistry() wired substrate addresses
  • MIN_DISPUTE_RESOLVE_WINDOW() / MAX_DISPUTE_RESOLVE_WINDOW(), MIN_PROPOSAL_TTL() / MAX_PROPOSAL_TTL(), MIN_SWAP_TIMEOUT() / MAX_SWAP_TIMEOUT(), MAX_PAUSE_DURATION() on-chain bounds

Writes

  • proposeSwap(opts) propose a swap (supplier); decodes to { swapId }
  • acceptSwap(swapId) accept a proposal (receiver), locking escrow and arming the timeout
  • cancelProposal(swapId) cancel a proposal before acceptance (supplier)
  • receiverAttest(swapId) receiver attests physical cash delivery
  • confirmRelease(swapId) confirm release of escrow to the receiver (supplier)
  • timeoutReclaim(swapId) reclaim escrow after the release timeout (supplier)
  • proposalExpiry(swapId) expire a stale unaccepted proposal (permissionless)
  • raiseDispute(swapId, evidenceHash) raise a dispute on a locked swap
  • resolveDispute(swapId, releaseToReceiver) resolve a dispute (role-gated)
  • claimSwapEscrow(did, token) claim escrowed swap proceeds; decodes to { amount }
  • setDisputeResolveWindow(seconds), setMinSwapTier(tier), setProposalTtl(seconds), setSwapTimeout(seconds) governance setters

Events

  • getSwapProposed, getSwapAccepted, getReceiverAttested, getSwapReleased
  • getSwapCancelled, getSwapExpired, getSwapTimedOut
  • getDisputeRaised, getDisputeResolved
  • getSwapProceedsEscrowed, getSwapEscrowClaimed, getParamSet

compliance

Wraps ComplianceCascade, the read-only KYC / sanctions / PEP / AML verdict oracle. Deprecated (2026-06-15): its candidate path is known-vulnerable to caller-omission bypass and no production consumer binds it; it is retained only for coexistence. Settlement consumers, including N1 Gate-9, bind ComplianceCompleteness (the complianceCompleteness namespace) instead. Reads-only namespace: no writes, no events.

Reads

  • checkCompliance(subjectDid, profile): full KYC / sanctions / PEP / AML evaluation against a profile, returns ComplianceResult.
  • isCompliantForJurisdiction(subjectDid, jurisdictionTag): boolean pass for a jurisdiction's default profile.
  • isCompliantForProfile(subjectDid, profile): boolean pass for an explicit profile.
  • isCompliantForProfileWithCandidates(subjectDid, profile, candidateAttestationIds): boolean pass restricted to specific candidate attestation ids.
  • getDefaultProfile(jurisdictionTag): the registered default ComplianceProfile for a jurisdiction.
  • hasValidKycAtMinimumTier(subjectDid, kycMethodIdPrefix, minimumTier): KYC gate for one prefix, returns { valid, attestationId, tierFound, expiresAt }.
  • hasAnyKycAtMinimumTier(subjectDid, kycMethodIdPrefixes, minimumTier): KYC gate across prefixes, returns { found, methodId, attestationId }.
  • hasAllSanctionsClear(subjectDid, sanctionsMethodIds, maxAge): boolean, all listed methods clear within maxAge.
  • hasFreshSanctionsClear(subjectDid, sanctionsMethodIds, maxAge): sanctions detail { clear, attestationId, lastCheckedAt }.
  • hasPepScreen(subjectDid, pepMethodIds, maxAge): PEP screen { screened, flagged, attestationId }.
  • attesterRegistry(), identityAttestations(), identityRegistry(), revocationRegistry(): wired substrate addresses.

Constants

  • CASCADE_DOMAIN_V1(): compliance-cascade namespace tag (bytes).
  • MAX_AML_RISK_SCORE_BP(): maximum AML risk score (basis points).
  • MAX_KYC_TIER(), MIN_KYC_TIER(): KYC tier bounds.

Types exported: ComplianceProfile (jurisdiction requirement set), ComplianceResult (full evaluation output). A separate methodIds module ships greppable v1 constants: COMPLIANCE_METHOD_IDS (35-method roster), COMPLIANCE_DOMAINS, COMPLIANCE_JURISDICTIONS_V1, COMPLIANCE_DEFAULT_PROFILE_TAGS, COMPLIANCE_METHOD_COUNT_V1, plus the ComplianceMethodId / ComplianceDomain / ComplianceJurisdictionV1 / ComplianceDefaultProfileTag literal types.

complianceCompleteness

Wraps ComplianceCompleteness (CC2), the read-only omission-proof compliance screen. It distinguishes an authoritative clear from a silent coverage gap via *Authoritative / *GateArmed / sourceComplete flags. N1 Gate-9 binds it contract-to-contract. The mutating surface (add/tighten method-id governance) is CONFIG_ADMIN and not wrapped; the namespace exposes reads plus one event.

Reads

  • checkComplianceFull(subjectDid, jurisdictionTag): full omission-aware verdict, returns ComplianceFullVerdict.
  • screenSubjectForJurisdiction(subjectDid, jurisdictionTag, positiveCandidateIds): boolean screen restricted to positive candidate attestation ids.
  • getGovernedProfile(jurisdictionTag): the CONFIG_ADMIN-set governed ComplianceProfile.
  • identityAttestations(), identityRegistry(), revocationRegistry(): wired substrate addresses.

Events

  • events.getGovernedProfileSet({ fromBlock?, toBlock?, jurisdictionTag? }): governed-profile updates; jurisdictionTag is an indexed string (filter by plaintext, decoded field carries the keccak256 hash).

Constants

  • COMPLETENESS_DOMAIN_V1(): completeness namespace tag.
  • ADVERSE_LOOKBACK_WINDOW(): adverse-media lookback window (seconds).
  • AML_FAMILY_PREFIX(), PEP_FAMILY_PREFIX(), SANCTIONS_FAMILY_PREFIX(): method-id family prefixes.
  • MAX_AML_RISK_SCORE_BP(), MAX_KYC_TIER(), MIN_KYC_TIER(): score/tier bounds.
  • MAX_PEP_METHOD_IDS(), MAX_SANCTIONS_METHOD_IDS(): per-profile method-id caps.

Types exported: ComplianceFullVerdict (omission-aware output), GovernedProfileSetEvent; re-exports ComplianceProfile from the compliance namespace.

travelRule

Wraps TravelRule, the read-only FATF travel-rule screen. Apps read thresholds and cross-border / attestation gates; enforcement is invoked by N1 contract-to-contract. No user-facing on-chain submission surface (threshold seeding is governance), so the namespace exposes reads plus one event.

Reads

  • checkTravelRule({ originatorDid, beneficiaryDid, token, amount }): full evaluation (threshold + cross-border + attestation gates), returns TravelRuleResult.
  • requiresTravelRuleForTransfer({ originatorDid, beneficiaryDid, token, amount }): boolean, does the transfer require travel-rule compliance.
  • getThresholdForToken(token): configured threshold in native units (0 if unconfigured).
  • isAboveThresholdForToken(token, amount): boolean at/above the token threshold.
  • isTokenConfigured(token): boolean, token has a configured threshold.
  • configuredTokenCount(): count of tokens with a configured threshold.
  • maxThresholdByDecimals(decimals): ceiling threshold for a token-decimals bracket.
  • jurisdictionOf(did): DID country-of-residence, returns { countryCode (bytes2), found }.
  • hasOriginatorAttestation(did): returns { has, attestationId, commitmentHash }.
  • hasBeneficiaryAttestation(did): returns { has, attestationId, commitmentHash }.
  • attesterRegistry(), identityAttestations(), identityRegistry(), revocationRegistry(): wired substrate addresses.

Events

  • events.getThresholdSeeded({ fromBlock?, toBlock?, token? }): per-token threshold seedings (token, thresholdNative, decimals, symbol).

Constants

  • TRAVEL_RULE_DOMAIN_V1(): namespace tag.
  • FATF_BASELINE_THRESHOLD_USD_CENTS(): FATF baseline threshold (USD cents).
  • MIN_ORIGINATOR_ATTESTATION_FRESHNESS(), MIN_BENEFICIARY_ATTESTATION_FRESHNESS(), MIN_COUNTRY_ATTESTATION_FRESHNESS(): freshness floors (seconds).
  • ENCODING_ASN1(), ENCODING_ISO20022(): encoding tags.
  • METHOD_PREFIX_ORIGINATOR(), METHOD_PREFIX_BENEFICIARY(), METHOD_COUNTRY_OF_RESIDENCE(), METHOD_THRESHOLD_CHECK(), METHOD_THRESHOLD_USD_1000(), METHOD_ORIGINATOR_ATTEST(), METHOD_ORIGINATOR_ASN1(), METHOD_ORIGINATOR_ISO20022(), METHOD_BENEFICIARY_ATTEST(), METHOD_BENEFICIARY_ASN1(), METHOD_BENEFICIARY_ISO20022(): attestation method-id constants.

Types exported: TravelRuleResult (full evaluation output), ThresholdSeededEvent.

lending

Wraps AgentLiquidityPool (N4), the agent-credit facility: LPs deposit settlement-token liquidity for shares; agents borrow against stake and reputation caps; overdue loans are liquidated against the agent's stake (haircut to reserve). Full-wrap namespace: reads, writes (direct calls, no signatures), and events.

Reads

  • loanOf(agentId): per-agent Loan record.
  • previewBorrowLimit(agentId): returns { limit, available }.
  • outstandingDebtOf(agentId): principal + accrued fee.
  • isInDefault(agentId): boolean, loan past due.
  • sharesOf(lp): LP share balance.
  • totalAssets(), internalAssets(), idleLiquidity(), totalShares(), totalOutstandingPrincipal(), reserveBalance(), paused(): pool state.
  • advanceRateBps(), borrowFeeBps(), haircutBps(), reserveFeeBps(), utilizationCapBps(), minBorrow(), minDeposit(), loanDuration(), capProvisional(), capCertified(), capPremium(): economic parameters.
  • settlementToken(), lpEligibleSchemaId(), agentRegistry(), agentReputation(), attestationsRegistry(), builderRegistry(), guardianRegistry(), protocolConfig(), revocationRegistry(): wired substrate addresses.

Writes

  • deposit({ assets, lpDid }): deposit for LP shares, decodes to { mintedShares }.
  • redeem({ shares, to }): redeem shares for assets, decodes to { assets }.
  • borrow({ agentId, amount, to }): borrow against stake + reputation cap.
  • repay(agentId, amount): repay (part of) a loan.
  • liquidate(agentId): arm liquidation of an overdue loan (permissionless keeper).
  • applyLiquidationProceeds(agentId): apply seized-stake proceeds against an armed liquidation (permissionless).
  • seedReserve(amount): seed the first-loss reserve.
  • setAdvanceRate(bps), setBorrowFee(bps), setHaircut(bps), setReserveFee(bps), setUtilizationCap(bps), setLoanDuration(seconds), setMinBorrow(amount), setMinDeposit(amount), setReputationHardCaps({ provisional, certified, premium }): FACILITY_ADMIN parameter setters.

Events

  • events.getDeposited({ lp?, lpDid? }), events.getRedeemed({ lp?, to? }): LP flows.
  • events.getBorrowed({ agentId?, to? }), events.getRepaid({ agentId?, payer? }): agent flows.
  • events.getLiquidationArmed({ agentId? }), events.getLiquidationProceedsApplied({ agentId? }): liquidation lifecycle.
  • events.getReserveAccrued(), events.getReserveSeeded({ from? }): reserve movements.
  • events.getParamSet({ key? }): parameter changes (indexed param-name hash).

Constants

  • ADVANCE_RATE_MAX_BPS(), BORROW_FEE_MAX_BPS(), RESERVE_FEE_MAX_BPS(), UTILIZATION_CAP_MAX_BPS(), HAIRCUT_MIN_BPS(): bps bounds.
  • MIN_LOAN_DURATION(), MAX_LOAN_DURATION(), DEFAULT_GRACE_PERIOD(): duration bounds (seconds).

Types exported: Loan plus the nine event types (DepositedEvent, RedeemedEvent, BorrowedEvent, RepaidEvent, LiquidationArmedEvent, LiquidationProceedsAppliedEvent, ReserveAccruedEvent, ReserveSeededEvent, ParamSetEvent).

grants

Wraps GrantDistributor, activity-gated onboarding grants to agents attributed to their sponsoring builder, on a tapering schedule with a timelocked clawback. Full-wrap namespace: reads, writes (direct calls, no signatures), and events. The grant program is launching with no awards.

Reads

  • grantOf(agentId): per-agent Grant record, or null if never claimed.
  • params(): program GrantParams.
  • isClaimable(agentId, caller): whether caller may currently claim for an agent.
  • hasClaimed(agentId): boolean, agent already claimed.
  • currentGrantAmount(): current tapered amount for a fresh claim.
  • grantsClaimedByBuilder(operatorId): grants claimed by a builder.
  • grantsRemainingInProgram(), totalGrantsClaimed(), cumulativeGranted(): program totals.
  • poolBalance(), poolToken(): grant-pool state.
  • activitySource(): N1-settlement activity-score source.
  • treasury(): clawback + sweep sink.
  • paused(): whether claims are paused.
  • agentRegistry(), agentReputation(), builderRegistry(), protocolConfig(): wired substrate addresses.

Writes

  • claimGrant(agentId): claim the activity-gated onboarding grant (attributed to the agent's builder).
  • proposeClawback(agentId, reasonHash): arm the clawback timelock (CLAWBACK_ADMIN).
  • executeClawback(agentId): execute a matured clawback proposal.
  • cancelClawback(agentId): cancel a pending clawback proposal.
  • setGrantParams(params): update program parameters (GRANT_ADMIN).
  • setActivitySource(source): set the N1-settlement activity source.
  • setTreasury(treasury): set the clawback/sweep sink.
  • sweepPool(amount): sweep unallocated pool funds to Treasury.

Events

  • events.getGrantClaimed({ agentId?, operatorId?, builderKey? }): claims.
  • events.getGrantClawbackProposed({ agentId? }), events.getGrantClawbackCancelled({ agentId? }), events.getGrantClawedBack({ agentId? }): clawback lifecycle.
  • events.getGrantParamsUpdated(): parameter updates.
  • events.getActivitySourceSet({ oldSource?, newSource? }): activity-source changes.
  • events.getPoolSwept({ to? }): pool sweeps.
  • events.getTreasurySet({ oldTreasury?, newTreasury? }): treasury changes (contract event TreasurySet).

Constants

  • CLAWBACK_TIMELOCK(): clawback proposal timelock (seconds).
  • MAX_GRANTS_PER_BUILDER_CEIL(): per-builder grant-count ceiling.
  • MAX_GRANT_AMOUNT(): single-grant amount ceiling.
  • TAPER_TRANCHES(): number of taper tranches.
  • MAX_PAUSE_DURATION(): max single pause duration (seconds).

Types exported: GrantState enum (NONE=0, CLAIMED=1, CLAWED_BACK=2), Grant, GrantParams, plus the eight event types (GrantClaimedEvent, GrantClawbackProposedEvent, GrantClawbackCancelledEvent, GrantClawedBackEvent, GrantParamsUpdatedEvent, ActivitySourceSetEvent, PoolSweptEvent, GrantTreasurySetEvent).

client

The SDK entry point and unified write surface. Constructs the namespaced AdunaiClient over a viem PublicClient (and optional WalletClient), and returns a TxBuilder from every write method. Phase 0 stance: mainnet is rejected at construction, wallet/SDK chain mismatch throws, and an EntryPoint version other than 0.7 throws.

Functions

  • createAdunaiClient(opts): builds the AdunaiClient; resolves the network, enforces the chain-match and EntryPoint checks, and wires all namespaces.

Classes

  • TxBuilder: the write surface returned by every write method; exposes request (raw { to, data, value }), abi, simulate(), gasEstimate(opts), and send(opts) with a per-call via: 'eoa' | 'aa' route override.

Types

  • AdunaiClient: the namespaced client; carries network plus every contract namespace.
  • AdunaiClientOptions: constructor input (publicClient, optional walletClient, network, optional accountAbstraction; indexer typed never).
  • SendOptions: { via?: 'eoa' | 'aa' } per-call route override for send().
  • GasEstimateOptions: alias of SendOptions.
  • SimulationResult<TResult>: decoded result plus the raw request.
  • TxReceipt: { hash, blockNumber, status, via, userOpHash? }.
  • AccountAbstractionAdapter: the ERC-4337 bundler seam interface (prepareUserOp, estimateUserOp, sendUserOp, waitForReceipt; readonly entryPointVersion, entryPointAddress, accountAddress).
  • EntryPointVersion: literal union derived from the supported set (Phase 0: '0.7').
  • TxRequest: inbound { to, data, value? } for the adapter.
  • UnsignedUserOp: EntryPoint v0.7 user-op shape prior to signing.
  • SignedUserOp: UnsignedUserOp & { signature }.
  • UserOpHash: Hex alias for a user-op hash.
  • UserOpGas: gas-limit breakdown for a user op.
  • UserOpReceipt: bundler-confirmed user-op receipt.

Constants

  • SUPPORTED_ENTRYPOINT_VERSIONS: ['0.7'] as const; the only accepted EntryPoint versions in Phase 0.

eip712

Per-contract EIP-712 domain separators, typed-data type-sets, and typed-data builders. Each registry has an independent domain and nonce space; the string encoding of each type-set byte-matches the Solidity typeHash. Covers IdentityRegistry, HandleRegistry, AttestationsRegistry, IdentityAttestations, RevocationRegistry, VouchingRegistry, SelectiveDisclosure, AgentRegistry, AgentSettlement (and forwarder), and DelegationRegistry.

EIP-712 typed data

  • identityRegistryDomain(opts): domain for Adunai IdentityRegistry, version 1.
  • handleRegistryDomain(opts): domain for Adunai HandleRegistry, version 1.
  • attestationsRegistryDomain(opts): domain for Adunai AttestationsRegistry, version 1.
  • identityAttestationsDomain(opts): domain for Adunai IdentityAttestations, version 1.
  • revocationRegistryDomain(opts): domain for Adunai RevocationRegistry, version 1.
  • vouchingRegistryDomain(opts): domain for Adunai VouchingRegistry, version 1.
  • selectiveDisclosureDomain(opts): domain for Adunai.SelectiveDisclosure, version 1.
  • agentRegistryDomain(opts): domain for Adunai AgentRegistry, version 1.
  • agentSettlementDomain(opts): domain for Adunai AgentSettlement (N1), version 1.
  • agentSettlementForwarderDomain(opts): domain for Adunai AgentSettlementForwarder, version 1.
  • delegationRegistryDomain(opts): domain for Adunai DelegationRegistry (N6), version 1.
  • buildDelegationActionTypedData(domain, message): delegate-signed Action permit, verified against the DelegationRegistry domain.
  • buildDelegationGrantTypedData(domain, message): controller-signed Grant permit (createGrant).
  • buildDelegationSetCapTypedData(domain, message): controller-signed SetCap permit (additional-token cap).

Constants

  • AdunaiDomainName: union of the three primary domain-name literals.
  • DelegationAction: uint64 scope-bit discriminants (PAYMENT, AGENT_CASH_OUT, SAVINGS_DEPOSIT, GROUP_CONTRIB).
  • Type-sets (each an as const mirroring the contract typehash): RotateKeyTypes, SetRecoveryConfigTypes, RevokeIdentityTypes, TransferHandleTypes, SetPrimaryHandleTypes, ClearPrimaryHandleTypes, RegisterInstitutionalByDIDTypes, IssueAttestationTypes, IssueAttestationBySubjectTypes, ConsentToAttestationTypes, RevokeAttestationTypes, ReleaseAttestationTypes, SelfRevokeKeyTypes, SelfRevokeDIDTypes, RotateKeyRevocationTypes, AddKeyTypes, ScheduleRotationRevocationTypes, SetPrimaryKeyTypes, GuardianRevokeKeyTypes, VouchRevokeKeyTypes, EnrollmentGrantTypes, CashLegTypes, AgentConsentTypes, DelegationActionTypes, DelegationGrantTypes, DelegationSetCapTypes, VouchTypes, RevokeVouchTypes, GrantDisclosureTypes, RevokeGrantTypes.

errors

The SDK error hierarchy. All errors descend from the abstract AdunaiError so consumers can instanceof AdunaiError. Two tiers: ABI-decoded contract reverts (AdunaiContractError plus per-contract subclasses) and SDK-side network / preflight / policy errors. Each error carries a stable string code and structured context.

Base and decoder

  • AdunaiError: abstract base; code and context on every subclass.
  • AdunaiContractError: decoded custom-revert (contract, errorName, args, rawData); base for all per-contract subclasses.
  • ContractName: union of decodable contract names.
  • decodeContractRevert(contract, rawData): turns raw revert data into an AdunaiContractError (scaffold: unknown reverts return errorName: 'UnknownRevert').
  • isAdunaiError(value): type guard for any SDK error.
  • isAdunaiContractError(value): type guard for a decoded contract revert.

Contract-revert subclasses

  • Shared: ZeroAddressError, SignatureExpiredError, InvalidSignatureError.
  • HandleRegistry: HandleAlreadyRegisteredError, HandleNotRegisteredError, NameTooShortError, NameIsReservedError, NotDIDControllerError.
  • AttestationsRegistry: SchemaNotRegisteredError, IssuerDIDRevokedError, SubjectDIDRevokedError, AttestationCapReachedError, SchemaNotRevocableError, IssuerSuspendedForSchemaError, MissingSubjectSignatureError, UnexpectedSubjectSignatureError, NotAccreditedIssuerError, NotRestrictedVerifierError.
  • PaymentsRouter: TokenNotWhitelistedError, AmountTooSmallToCoverFeeError, MissingAttestationError, BatchTooLargeError, BatchEmptyError, BatchArrayLengthMismatchError, UnexpectedBalanceChangeError, RemovalRequiresPauseError, NoPendingFeeIncreaseError, FeeIncreaseTimelockNotElapsedError.
  • AgentRegistry: AgentNotFoundError, AgentAlreadyRegisteredError, AgentNotRegisteredError, StakeBelowMinimumError, CooldownNotElapsedError, SlashStillPendingError, NoSlashPendingError, SlashTimelockNotElapsedError, TooManyServiceAreasError, ServiceAreaIndexOutOfBoundsError, HandleNotInstitutionalError, HandleNotVerifiedError.
  • Treasury (suffixed to avoid name collisions): TreasuryZeroAddressError, TreasuryInvalidRecipientError, TreasuryZeroAmountError, InsufficientETHBalanceError, InsufficientTokenBalanceError.
  • TimelockController + AccessControl: TimelockInvalidOperationLengthError, TimelockInsufficientDelayError, TimelockUnexpectedOperationStateError, TimelockUnexecutedPredecessorError, TimelockUnauthorizedCallerError, AccessControlUnauthorizedAccountError, AccessControlBadConfirmationError.

SDK preflight and input-validation errors

  • Payments preflight: TokenNotWhitelistedPreflightError, MissingAttestationPreflightError, BatchTooLargePreflightError, BatchEmptyPreflightError.
  • Agents preflight: MissingPhoneVerifiedAttestationPreflightError, InstitutionalHandleNotFoundPreflightError, InstitutionalHandleNotVerifiedPreflightError, InstitutionalHandleNotOwnedByDIDPreflightError, ServiceAreasEmptyPreflightError, TooManyServiceAreasPreflightError.
  • Cross-namespace preflight: DIDNotRegisteredError, DIDRevokedError, SchemaNotFoundError, ConsentRequiredError.
  • Input validation: InvalidCanonicalName, InvalidE164PhoneNumber, InvalidHandleDisplay.

Network and policy errors

  • Network tier: AdunaiNetworkError, AdunaiUserRejectedError, AdunaiTimeoutError.
  • SDK policy: MainnetNotSupportedInPhase0, ChainMismatch, UnsupportedEntryPointVersion, RouteNotAvailable, IndexerSupportPhase1, AdunaiDidVerificationFailed.

deployments

Network resolution plus the bundled Base Sepolia address manifest. Phase 0 supports 'base-sepolia' (addresses projected from the on-chain manifest), 'anvil' (consumer supplies addresses), and a custom NetworkConfig; mainnet is rejected. The Base Sepolia projection is generated from the manifest, not hand-edited.

Functions

  • resolveNetwork(input): maps 'base-sepolia' | 'anvil' | NetworkConfig to a resolved NetworkConfig; passes objects through, throws for 'anvil' without explicit addresses, throws MainnetNotSupportedInPhase0 for 'base'.

Types

  • ContractAddresses: the full per-contract address map (35 protocol contracts across the C2 groups).
  • NetworkConfig: { chainId, network, addresses }.
  • NetworkInput: 'base-sepolia' | 'anvil' | NetworkConfig.
  • BaseSepoliaDeployment: type of the bundled manifest projection.

Constants

  • baseSepoliaDeployment: the checksummed Base Sepolia manifest (chainId 84532, the 2026-07-01 fresh redeploy) with contracts, config.foundation/timelock/deployer, and launchTokens (USDC, USDT, EURC, cbBTC, WETH).

types

Branded primitive types (compile-time safety against bytes32 value confusion) and the contract enum literal-unions. Each branded type ships a validating from(value) constructor; some carry pure derivation/encoding helpers that mirror the on-chain functions. Enums are as const literal unions matching each contract's *Types.sol.

Branded types and constructors

  • Brand<T, B>: the brand machinery; Hex32 / Hex2 hex aliases.
  • DID: from(value) (hex32, non-zero), zero.
  • CanonicalName: from, zero, fromName(name) (HandleRegistry charset/length rules), fromPhone(e164) (strict E.164, fails closed), toName(canonical).
  • SchemaId: from, fromName(name) (mirrors canonicalSchemaId: keccak256(abi.encode("adunai.schema.v1", keccak256(name)))).
  • AttestationId: from.
  • AgentId: from, derive(did) (mirrors _deriveAgentId).
  • TransferId: from, derive(opts) (mirrors transferIdOf; pre-submission correlation only).
  • DataHash, EvidenceHash, ReasonHash: from.
  • MetadataHash, RecoveryConfigHash: from, zero.
  • Salt: from.
  • CountryCode: from, fromAlpha2(code), toAlpha2(code).
  • Region: from, zero, fromName(name), toName(region), normalize(name).
  • TimelockOperationId: from, derive(opts) (mirrors hashOperation), deriveBatch(opts) (mirrors hashOperationBatch).

Enums

  • HandleTier (BASE, INSTITUTIONAL).
  • InstitutionType (NONE, BANK, GOV, HEALTH, EDU, ORG, TELCO, UTILITY, PRESS).
  • ReservedCategory (NONE, PROTECTED, COUNTRY, INSTITUTION, RESERVED).
  • IssuancePolicy (OPEN, ACCREDITED, RESTRICTED).
  • WithdrawalCategory (Operations, ProtocolDev, Grants, AgentNetwork, Reserve, RegulatoryEngagement).
  • AgentTier (INDIVIDUAL, BUSINESS, LICENSED).
  • AgentStatus (REGISTERED, SUSPENDED, DEREGISTERED; no zero sentinel).
  • SlashCategory (FraudConfirmed, TheftConfirmed, NonDelivery, FeeViolation, Other, LendingDefault).
  • OperationState (Unset, Waiting, Ready, Done; matches OZ TimelockController).
Phase 0 · Base Sepolia testnet