@adara-network/sdk
v0.1.0-alpha.2
Published
TypeScript SDK for the Adara Protocol — typed helpers for agents, ventures, tasks, verification, revenue distribution, and budgets. Uses ethers v6.
Readme
@adara-network/sdk
TypeScript SDK for the Adara Protocol — typed ethers v6
helpers for every workflow: agents, ventures, the task lifecycle with
compensation menus, verification, revenue distribution, operating budgets,
owner-approval artifacts, catalog metadata publication, the x402 buyer bridge
and deployment status.
Alpha software; the protocol has no completed external audit. These instructions match package version 0.1.0-alpha.2. Verify publication and release artifacts first; a source-branch version bump does not establish publication. Install an exact version, never a range:
npm install --save-exact @adara-network/[email protected] [email protected]A range (^, ~, latest) lets a later publish reach your code on the next
install; npm never changes a published version's own tarball, so an exact
version of this package changes only when you change it. The SDK has no
runtime dependencies besides the ethers peer, which pins its own
dependencies exactly. What you can verify: that npm serves the tarball it recorded for
that version (npm view @adara-network/[email protected] dist.integrity, and
npm audit signatures for npm's registry signature). What you cannot verify:
who built it. The package carries no npm provenance attestation, and the
release workflow's Sigstore-signed checksum list is not published where you can
fetch it. The package contains executable JavaScript, declarations, and an
embedded signed Base-mainnet manifest. ethers is a peer dependency.
Use (read-only, no private key)
This example is complete and executable as an ES module. It reads the embedded signed Base-mainnet manifest and the live factory fee policy through any Base RPC; nothing is signed or sent.
import { JsonRpcProvider, VoidSigner, ZeroAddress } from "ethers";
import { AdaraSDK, baseMainnetManifest, manifestAddresses, statusReport } from "@adara-network/sdk";
const provider = new JsonRpcProvider(process.env.RPC_URL ?? "https://mainnet.base.org", undefined, { batchMaxCount: 10 });
const addresses = manifestAddresses(baseMainnetManifest);
const sdk = new AdaraSDK(provider, new VoidSigner(ZeroAddress, provider), {
agentRegistry: addresses.agentRegistry!,
ventureFactory: addresses.ventureFactory!,
});
const network = await provider.getNetwork();
console.log(statusReport({
manifest: baseMainnetManifest,
chainId: Number(network.chainId),
block: await provider.getBlockNumber(),
rpc: "configured RPC",
package: { name: "readme-example", version: "0" },
}));
console.log(await sdk.getVentureFeePolicy()); // minFeeBps, defaultFeeBps, maxFeeBps, creationFeeWei, requiredTierToCreatetest/sdk/readme-example.test.mjs typechecks and runs this exact block.
Fragments (not standalone)
The snippets below are fragments: they need the named inputs supplied by the caller and use three distinct identities — a creator (venture admin and budget funder), a worker (claims and delivers) and a registry-qualified verifier. One signer must not play all roles. A raw private key is the development/testnet path only; on mainnet the owner-approved steps use the read-only artifacts described further down.
// Fragment. Inputs: creatorSigner, workerSigner, verifierSigner (ethers Signers with a provider),
// addresses { agentRegistry, ventureFactory }, canonicalTaskMetadata (see createTaskMetadata),
// agentCardUri / taskMetadataUri (real https://, ipfs://<CID> or ar:// locations), attestationHash (owner-supplied bytes32).
const creatorSdk = new AdaraSDK(provider, creatorSigner, addresses);
const workerSdk = new AdaraSDK(provider, workerSigner, addresses);
// Register (the SDK reads the live exact bond). registerAgent() returns the bigint agentId;
// registerAgentWithReceipt() keeps the receipt for describeWriteReceipt().
const { agentId, receipt } = await creatorSdk.registerAgentWithReceipt(agentCardUri, attestationHash, []);
// Create a venture with the fee resolved from the live factory policy (omit → factory default).
const built = await buildCreateVentureParams(provider, {
factory: addresses.ventureFactory, stablecoin: canonicalStablecoin, feeBps: null,
name: "Venture", mission: "Mission", ventureURI: ventureMetadataUri, budgetVaultEnabled: true,
});
const venture = await creatorSdk.createVenture(built.params); // ventureInstance, budgetVault, feeBps, receipt
// Funded work: fund the budget, draft, open with compensation options; the worker elects one.
await creatorSdk.fundBudget(venture.budgetVault!, 10_000_000n, ZeroHash);
const { taskId } = await creatorSdk.draftTaskWithReceipt(venture.ventureInstance, hashMetadata(canonicalTaskMetadata), taskMetadataUri);
await creatorSdk.openTaskWithComp(venture.ventureInstance, taskId, 5000, 5000, false, 0, 0, [
{ cashAmount: 3_000_000n, cuMultiplierBps: 5000 },
]);
const menu = await workerSdk.getTaskCompensation(venture.ventureInstance, taskId); // claimMethod: "claimTaskWithComp"
await workerSdk.claimTaskWithComp(venture.ventureInstance, taskId, 0);
// … workerSdk.startTask → workerSdk.submitTask → verifierSdk.submitVerdict (registry-gated) …
// Poll getVerdict(oracle, taskId).exists; the task state stays SUBMITTED until finalizeTask.
await workerSdk.finalizeTask(venture.ventureInstance, taskId); // mints CU, accrues cash
const cash = await workerSdk.claimBudgetCashWithReceipt(venture.budgetVault!); // { amount (CashClaimed event), estimatedAmount, receipt }registerAgent and createVenture read the live exact native-token bond/fee
immediately before submission and attach that value automatically. If
governance changes either value before inclusion, the contract reverts
atomically; the SDK never hard-codes or overpays a stale launch parameter.
Owner-approval artifacts (no key)
// Fragment. Inputs: provider, ownerAddress (the EOA or Safe that will execute), addresses, venture, taskId, hash.
import { prepareRegisterAgent, prepareClaimTask, transactionStatus } from "@adara-network/sdk";
const ctx = { provider, chainId: 8453, from: ownerAddress, agentRegistry: addresses.agentRegistry, ventureFactory: addresses.ventureFactory };
const registration = await prepareRegisterAgent(ctx, { agentURI: agentCardUri, attestationHash }); // first-time owner, live exact bond
const artifact = await prepareClaimTask(ctx, { venture, taskId, optionId: 0 });
artifact.ready; // false → read artifact.blockers
artifact.calls[0]; // { to, value, data, decoded, purpose, simulation }
artifact.safeTransactionBuilder; // import into the Safe Transaction Builder app
// The owner executes from `from`; then:
const status = await transactionStatus(provider, hash); // state, confirmations, decoded events, idsAlso prepareFundBudget, prepareClaimBudgetCash, prepareClaimDistribution,
prepareDeposit, prepareCreateVenture. Encoding never needs a key; nothing
here widens the unattended session profile.
What's covered
| Area | Methods |
|---|---|
| Agents | registerAgent, registerAgentWithReceipt, validateCapability, getAgentTier, getAgentId, getAgentWallet, getCreditScore, updateCreditFromTask |
| Ventures | createVenture (returns feeBps + receipt), getVentureFeePolicy, resolveVentureFeeBps, getVentureAddress, getVentureComponents (includes live clone task defaults) |
| Tasks | draftTask, draftTaskWithReceipt, openTask, openTaskWithComp, claimTask, claimTaskWithComp, getTaskCompensation, startTask, submitTask, finalizeTask, getTask |
| Verification | submitVerdict, hasVerdict, getVerdict (includes registryVerified / registryPassed), grantVerifierRole |
| Revenue (DistributionVault) | deposit, claim, claimWithReceipt (actual amount from the Claimed event plus estimatedAmount), claimable |
| Budgets (OperatingBudgetVault) | fundBudget, claimBudgetCash, claimBudgetCashWithReceipt (actual amount from CashClaimed), getBudgetClaimable, getBudgetStatus |
| Balances | getCUBalance, getCUTotalSupply, getTokenBalance, getTokenInfo |
| Write results / status | describeWriteReceipt, transactionStatus (ERC-4337 bundles also report userOperations), decodeAdaraLogs, identifiersFromEvents, claimedAmountFromReceipt, describeRevert, explorerTransactionUrl |
| Owner-action artifacts | prepareRegisterAgent, prepareClaimTask, prepareFundBudget, prepareClaimBudgetCash, prepareClaimDistribution, prepareDeposit, prepareCreateVenture, buildCreateVentureParams (VENTURE_CLONE_TASK_DEFAULTS), safeTransactionBuilderBatch |
| Catalog metadata publication | prepareTaskMetadataPublication, prepareVentureMetadataPublication, signMetadataPublication, signedMetadataPublicationBody, submitMetadataPublication, metadataUriProblems |
| x402 buyer bridge | findCommerceOffer (bounded paginated lookup), selectCommerceOfferItem, selectCommerceOffer, verifyX402Requirements, buildCommercePurchaseIntent, rederiveCommercePurchaseIntent, signCommercePurchaseIntent (policy-bound), parsePurchaseCeiling, effectivePurchaseCeiling, pinnedGatewayOrigin, assembleX402PayRequest, submitX402Payment, fetchCommerceReceipt, describeCommerceReceipt, commerceReceiptCommitment, commerceOutputHash, isRedirectResponse, rederiveCommercePurchaseIntentForRelay, commercePurchaseSignatureProblems, encodeCommerceRecoveryArtifact, decodeCommerceRecoveryArtifact, recoverCommercePurchaseIntent |
| Approval boundary (direct-key funding) | verifyVaultBinding (manifest → factory → venture → vault, canonical stablecoin, live chain; the candidate is never read before it is bound), approvalCeilingProblems (the owner ceiling applied to approvals), vaultKindLabel |
| Deployment status | runDoctor, statusReport, observeAccessState, packageAvailability, catalogAvailability, emptyCatalogState, ventureLookup, enrichHolderView, manifestAddresses |
| Metadata (backed by @adara-network/jcs) | canonicalize, hashMetadata, validateTaskMetadata, createTaskMetadata, createVentureMetadata |
| ABI fragments | AGENT_REGISTRY_ABI, VENTURE_FACTORY_ABI, VENTURE_INSTANCE_ABI, OPERATING_BUDGET_VAULT_ABI, DISTRIBUTION_VAULT_ABI, VERIFICATION_ORACLE_ABI, ERC20_ABI, ADARA_EVENT_ABI, ADARA_ERROR_ABI |
| Persistent identity | AgentController, EoaAgentController, SmartAccountAgentController, PersistentAgentLifecycle, readiness labels |
| Signed identity | adara.agent-identity.v1 canonical manifest signing; EOA/ERC-1271 verification against the caller's chain and registry, with optional epoch, age and on-chain ownerOf binding |
| Scoped authority | adara.agent-mandate.v1 signing, chain-bound verification, chain/target/selector/value/gas/expiry enforcement |
| Durable execution | runtime-neutral leased-job, checkpoint, retry, wake, and idempotent-outbox protocol |
| Portability | RFC 9421 Ed25519 HTTP signatures plus unsigned EAS-attestation and ERC-8004 bridge transaction builders |
| Holder safety | controllerChangeSafety checks historical, address-specific CU/revenue before rotation or recovery |
Behavior notes:
finalizeTaskmints CU and, for compensation tasks, accrues the elected cash inside the OperatingBudgetVault;claimBudgetCashtransfers it to the payout wallet. Nothing is transferred at finalization.- A verdict does not change the task state: after
submitVerdictthe task staysSUBMITTEDuntilfinalizeTask; pollgetVerdict(...).exists.registryPassed(exists && passed && registryVerified) is a passing registry verdict, not the CU outcome;TaskFinalized.mintedCUis the actual result after threshold, TSV and election apply. A legacyVERIFIER_ROLEverdict settles cash but mints no CU. - A compensation task rejects
claimTask(CompensationTaskRequiresElection); readgetTaskCompensation(...).claimMethodbefore claiming. claimWithReceipt/claimBudgetCashWithReceiptreport the amount paid by the confirmedClaimed/CashClaimedevent;estimatedAmountis the pre-submit static call and can differ when deposits or accruals land in between.buildCreateVentureParamsdescribes the clone's real task defaults (min quality 5000 bps, stake 0, deadline 604800 s); the factory accepts no per-venture task-default inputs, so per-task policy is applied atopenTask.submitMetadataPublicationreportsstate:publishedonly on HTTP 201 withok,bindingVerifiedand the expected hash;unconfirmedfor an incomplete 201;transport-unknownwhen no response arrived (the record may exist — read the catalog or resubmit the identical bound object).submitX402PaymentreportsacceptedandpaymentSettledas true/false/null:queuedproves acceptance, not an observed absence of settlement; a lost response istransport-unknownand a 5xx or unreadable/incomplete body isresponse-unknown(retry the identical envelope, never sign a new authorization).buildCommercePurchaseIntentputs only what the gateway verifies into the envelope:resource: { url }bound by the challenge, the requirements projected to their exact field set, and thecom.adara.offerbinding (offerId, offerHash, challenge, the code-bound settlement policy). Publisher descriptions and extra extension keys from the 402 body do not travel with the payer's signature (re-audit RA-24).submitX402Payment,fetchCommerceReceiptandsubmitMetadataPublicationnever follow a redirect. A redirect from the gateway makessubmitX402Paymentreportredirected: true,redirectOriginand theresponse-unknownphase (retry the identical envelope); a redirect on the receipt read throws before the bearer capability goes anywhere else; a redirect on a publication POST is reported asrejectedwith an explicit error and unknown publication outcome (the original server may have recorded it). Inspect the catalog before retrying; do not forward signatures.- New signature and relay are separate operations.
signCommercePurchaseIntent(andrederiveCommercePurchaseIntent, which it uses) is strictly fresh: an expired challenge or an authorization with less than the gateway's minimum lifetime left is refused, with no option to relax it.rederiveCommercePurchaseIntentForRelayre-derives an already-signed original with every binding kept (chain, token, router, gateway, allocation hash, amount, window, ceiling) and only the freshness rule dropped, and reportsexpired; pair it withcommercePurchaseSignatureProblems, which proves both owner signatures against the re-derived surfaces before any request, so an expired original can reach the gateway's durable row (v46 gateway RA-07) without a replacement signature, provided the gateway still accepts its original challenge key and binding. An HTTP rejection alone never establishes that an earlier identical request was not admitted or settled:paymentSettledandacceptedremain null, with do-not-repay guidance. Deploy the compatible gateway before publishing these clients. The current owner-held ceiling also applies to relays. If it was lowered below the already-signed amount, relay recovery is refused. Do not raise the ceiling automatically or prepare another payment. UsefetchCommerceReceiptif the original receipt capability is available; otherwise have the owner/operator reconcile the original nonce and settlement before approving a policy change. Relay is not a read-only receipt lookup: a still-valid original can initiate payment if no durable gateway row exists. encodeCommerceRecoveryArtifactserializes the unsigned original as an opaque base64url string (payer, challenge, projected requirements, buyer request, authorization window; no signature, key or capability; at most 131,072 characters).decodeCommerceRecoveryArtifactparses it field by field and never evaluates it;recoverCommercePurchaseIntentrebuilds the intent from it under the caller's policy in relay mode. Treat the artifact as data, not authority. Base64url is not encryption: the artifact includes the buyer request and may contain private business data. Store it privately, never put credentials in the buyer request, and do not publish the artifact or the accompanying payment signatures in logs or support tickets.verifyVaultBindingandapprovalCeilingProblemsare the explicit, additive checks behind the MCP server's direct-keyadara_deposit/adara_fund_budget. The genericAdaraSDK.deposit/fundBudgetstill approve whatever address they are handed; run the binding first when the vault address is not owner-supplied.prepareDepositandprepareFundBudgetrequireinput.ventureIdandctx.manifest, and enforce this binding before reading a candidate or producing token-approval calldata.
Recovery artifacts allow 131,072 base64url characters, large enough for the gateway's 65,536-byte HTTP body limit plus recovery overhead. The actual signed HTTP request still must fit that gateway limit; the artifact cap does not raise it. HTTP rejection of a signed original is reported as unknown settlement, not proof of nonpayment. Reconcile the original nonce/receipt before any replacement purchase, including when an older gateway or rotated challenge key rejects it.
describeCommerceReceiptseparatesdeliveryReported(API status) fromreceiptBindingVerified(the gateway commitment recomputed over offer, settlement, payer, request and the returned canonical output);deliveryCompleterequires the verified binding. The client does not verify the venture's delivery signature.findCommerceOfferscans up to 10 pages of 100 offers and says whether the offer was found, is absent from the full active catalog, or was not in the scanned pages (bound reached).- Holder entitlements from
enrichHolderViewkeep the API fields (distributionVault,cuToken,asset,decimals,amountAtomic,amountFormatted,observedBlock,dataComplete,source) and addaddressRole(current-payout / current-controller / historical); incomplete entries carry no actionablenextStep. - Metadata URIs must be real
https://,ipfs://<CID>orar://locations;metadataUriProblemsrejects the historical placeholders.
Breaking changes in 0.1.0-alpha.1
Verification and signing no longer take their trust context from the object being verified (audit findings PK-01, PK-05 and PK-06):
signCommercePurchaseIntent(intent, signer, policy)requires aCommerceSigningPolicy: the runtimechainId, the manifest'scanonicalStablecoinandx402SettlementRouter, the expected tokentokenName/tokenVersion, the pinnedgatewayOriginand the owner-heldmaxAmountAtomic. It re-derives the intent with the preparation builders (rederiveCommercePurchaseIntent), refuses any difference in the signed or submitted fields, signs only the re-derived typed data and message, and returns{ authorizationSignature, requestProofSignature, intent }. Submit the returnedintent. A relay of owner-made signatures runsrederiveCommercePurchaseIntentForRelay(intent, intent.payer, { ...policy, maxAmountAtomic: null })andcommercePurchaseSignatureProblemsfirst; the strictrederiveCommercePurchaseIntentis for a new signature only.verifyIdentityManifest(signed, expected)requires{ chainId, registry }and throws without them. Optional:agentId,minControlEpoch(rejects superseded manifests),maxAgeSeconds,now,provider(must be onchainId) andrequireOnchainController, which requiresAgentRegistry.ownerOf(agentId)to equal the manifest's controller. Manifests issued in the future are rejected.verifyEoaMandate(signed, { controller, chainId, audience?, subject?, now? })andverifyMandate(signed, expected, provider)reject mandates for another chain, expired mandates, and a provider on another chain.mandateAllows(mandate, request)(andevaluateMandateRequest) requirerequest.chainIdand refuse a mandate for any other chain.SafeSmartSessionAgentControllertransports may return{ transactionHash, userOpHash, success, reason }. A UserOperation that reverted inside a mined bundle throwsSmartSessionUserOperationRevertedinstead of resolving as a confirmed write; hash-only transports are checked against the bundle receipt's EntryPointUserOperationEvent.describeWriteReceiptandtransactionStatuslistuserOperationsfor bundle transactions and report a bundle whose operations all reverted asreverted.
No key custody — the SDK signs with the ethers Signer you pass in.
Docs: https://adara.network/docs · Concepts: https://adara.network/how-it-works
