@peaqos/peaq-os-sdk is the opinionated TypeScript entry point for the Machine Financial Passport flow. Chain and API operations are exposed both as PeaqosClient instance methods and as standalone functions; wallet helpers are static methods and standalone functions, and the validation and hashing helpers are standalone functions only.
Every client is a peaq-mainnet client unless deployment.deploymentId names another record; the record supplies every contract address, the EventRegistry and the MCR URL. It runs one-transaction activation, machine management and the monetization client. Add svm: { rpcUrl } on new PeaqosClient<"svmEnabled"> for machines homed on Solana: see Solana (SVM).
Install
- Node.js: ≥ 22
- TypeScript: ≥ 5
- Peer dependency:
viem(^2.54.2) - Solana onboarding: needs the optional peers
@solana/web3.jsand@coral-xyz/anchor(the OWS signer’s@open-wallet-standard/coreships with the SDK) - Exports: ESM and CJS. No bundler workarounds.
dotenv is optional but recommended: PeaqosClient.fromEnv() reads from process.env, so import "dotenv/config" at the top of your entry file is the simplest way to load .env.
Environment variables
PEAQOS_SVM_NETWORK is a CLI variable. Contract addresses are never environment variables: they ship in the deployment record (see Smart contracts).
Machine Markets orchestration
Scale lives underclient.orchestration, the Machine Markets surface (machine identity and pairing proofs, signed with an EVM or a Solana wallet; skill registry, market search, orders, payments). Reach it by setting PEAQOS_ORCHESTRATION_URL (and optionally PEAQOS_API_KEY) before PeaqosClient.fromEnv(). Method reference: Orchestration (JS).
Client
PeaqosClient
The client is generic over its Solana mode: PeaqosClient<S extends SvmMode = SvmMode>, with SvmMode = "evmOnly" | "svmEnabled". The type parameter is not inferred from the config: passing svm without <"svmEnabled"> does not compile. fromEnv() and fromWallet() infer it themselves. See Solana (SVM).
{ deploymentId }. Defaults to { deploymentId: "peaq-mainnet" }. Public records: peaq-mainnet, agung-2026-08-28.{ rpcUrl, commitment? } (commitment defaults to confirmed). Required with new PeaqosClient<"svmEnabled">; the Solana record is the one the selected deployment names.Receives peaq RPC retry (
kind: "retry") and per-operation call-count (kind: "calls") events.PeaqosClient instance. toJSON() and util.inspect output redact the private key, the API key and any key in the RPC URL ("[REDACTED]").
Other RPC endpoints are available. See Public RPC endpoints.
Errors: ValidationError: empty rpcUrl, or a privateKey that is not 0x + 64 hex. DeploymentConfigError: DEPLOYMENT_UNKNOWN for an unknown deployment.deploymentId; DEPLOYMENT_UNAVAILABLE for svm on a record with no Solana half (agung-2026-08-28). OrchestrationConfigError: an orchestrationUrl that is not http(s).
fromEnv
fromEnv() reads PEAQOS_RPC_URL and PEAQOS_PRIVATE_KEY (required), and optional PEAQOS_DEPLOYMENT_ID (trimmed; unset, empty or blank selects peaq-mainnet; an unknown value throws DeploymentConfigError DEPLOYMENT_UNKNOWN), PEAQOS_SVM_RPC_URL, PEAQOS_ORCHESTRATION_URL and PEAQOS_API_KEY. With PEAQOS_SVM_RPC_URL set it returns a PeaqosClient<"svmEnabled">, otherwise a PeaqosClient<"evmOnly">. It reads no contract address.
PeaqosClient. All required env vars must be set (see Environment variables).
Errors: ValidationError: a required env var missing or empty. DeploymentConfigError: DEPLOYMENT_UNKNOWN for an unknown PEAQOS_DEPLOYMENT_ID; DEPLOYMENT_UNAVAILABLE for PEAQOS_SVM_RPC_URL on agung-2026-08-28. OrchestrationConfigError: a PEAQOS_ORCHESTRATION_URL that is not http(s).
fromWallet
PeaqosClient from an OWS vault wallet. A config with svm returns PeaqosClient<"svmEnabled">; without it, PeaqosClient<"evmOnly">. When owsSigning is true (default), signing routes through OWS: the key is decrypted only per-sign and wiped immediately after. When false, the key is decrypted at construction and signing uses viem directly.
Vault passphrase. Pass
undefined to fall back to the OWS_PASSPHRASE env var.Client config without
privateKey (the wallet provides the signer).PeaqosError: wallet not found, passphrase missing, or OWS signing failure. With owsSigning: false a wrong passphrase throws at construction (eager decrypt). With owsSigning: true a wrong passphrase surfaces on the first sign call, and key material is never decrypted at construction.
Wallets (OWS)
Wallet lifecycle helpers (createWallet, importWallet, importWalletMnemonic, listWallets, getWallet, exportWallet, deleteWallet, plus the extractPeaqAddress utility) back the Open Wallet Standard integration: mnemonic-backed encrypted vault, multi-chain accounts (peaq, Base, Ethereum, Solana, Bitcoin, etc.). Lifecycle helpers are available as module-level imports and as static methods on PeaqosClient; the PeaqosClient.fromWallet factory wires a vault wallet directly into a client (OWS-native signing by default). The JS package bundles @open-wallet-standard/core as a regular dependency; no separate peer install is required. The raw-key constructor and fromEnv flow keep working unchanged. Full reference on the Wallets page.
generateKeypair
secp256k1 privateKey and its derived address. No chain interaction. The private key never touches disk.
OWS wallet lifecycle
OWS wallet helpers are available as staticPeaqosClient methods and standalone functions. They derive multi-chain accounts, keep wallet material in an encrypted OWS vault, and return public WalletInfo metadata.
@peaqos/peaq-os-sdk. createWallet, importWallet, importWalletMnemonic, exportWallet, and fromWallet require a passphrase argument or OWS_PASSPHRASE. options.vaultPath can point at a custom vault directory. fromWallet can sign through OWS (owsSigning=true, default) so key material is decrypted only for the signing operation.
Frozen object with
id, name, createdAt, keyType, peaqAddress, and accounts. Each account has accountId, address, chainId, network, and derivationPath.Accessors
All accessors are read-only. The private key is held in an ECMAScript#private field: never exposed through the public surface and redacted in JSON.stringify and util.inspect.
Activation and machine management
Available on every client. The seven role contracts and the record’sEventRegistry come from the SDK’s snapshot (DEPLOYMENTS, resolveDeployment), resolved at construction with no network call. Before an activation or management write the SDK checks the six role addresses against InfoDesk.peer(role); InfoDesk itself is pinned by the record, and the EventRegistry has no InfoDesk role and is used as recorded. Addresses are never accepted from callers. Every function below is a PeaqosClient method and a package-root export taking the client first. Machine IDs are bigint; a number throws ValidationError. Concepts: Economics 2.0.
activateMachine
MachineStateAndSync.activateMachine: mints the ERC-721 in MachineRegistry (token ID equals machine ID), stores the DID document, bonds the tier in MachineSubscription, and records the home chain. The signer becomes owner and bond payer. The preflight requires the MachineSubscription to be the authority chain (NOT_ECONOMIC_AUTHORITY otherwise): from 0.13.0 it reads isAuthorityChain() and falls back to isEconomicAuthority() only when the contract does not have the new function, never on a transport failure and, once the machine ID is computed, both MachineStateAndSync technical pause flags clear (TECHNICALLY_PAUSED), before any approval. This is the peaq-homed flow; with chain: "solana" the same entry point runs the Solana phases described under Solana (SVM).
ActivateMachineResult: machineId, owner, controller, tier, bondAmount, voucherCreditApplied, netPeaqAmount, transactionHash, chainId, contract, method, receipt, events (onboarded, minted, activated), subscription (the re-read subscription state) and isHomedLocally. Amounts come from the receipt. Success requires MachineOnboarded, MachineMinted, and Activated from the right contracts (matched by emitting address) plus a matching post-state read. The write is never retried; a receipt timeout throws RECEIPT_UNAVAILABLE carrying the hash.
activateMachineWithUsdt
Same activation, bond settled in USDT through SubscriptionTokenProvisionPool. Not usable on peaq mainnet: the pool has no USDT token configured, so the USDT quote and the write both revert. Requires maxUsdtAmount, taken from previewMachineActivationWithUsdt(...) after applying slippageBps.
previewMachineActivation, previewMachineActivationWithUsdt
machineId, bondAmount, voucherCredit, netPeaqAmount, balance, approvalRequired. Throws MACHINE_ID_MISMATCH and MAX_NET_PEAQ_EXCEEDED; a low balance is returned, not thrown.
computeMachineId
Reads
getMachineOwner, getMachineAvailability and getMachineManagementState return a tagged result (chain: "peaq" | "solana"), getMachineActivationState returns the Solana-aware state, and all four answer for a machine homed on Solana: see Solana (SVM).
Lifecycle and subscription
maxNetPeaqAmount, USDT writes maxUsdtAmount; take both from the matching preview. USDT writes are not usable on peaq mainnet (no USDT token configured in the pool). The SDK re-quotes before simulation and never raises an accepted bound. Owner or controller may sign; credits accrue to the owner.
Ownership (ERC-721)
DID updates
AUTHENTICATION_REWRITE_REQUIRED before submission. Ownership and DID writes accept a synchronous onTransactionSubmitted(submission) callback.
previewMachineAction
Side-effect-free preview for ownership and DID actions (not suspend/resume): contract, method, current state, intended effect. Never simulates, signs, or submits.
Machine-ID helpers
validateMachineId asserts and returns nothing. Canonical decimal strings at every JSON, URL, and log boundary. No Number(bigint), no leading zeros except "0".
Solana (SVM)
Machines can be homed on Solana. The SDK keeps one entry point per operation: the samegetMachineOwner, activateMachine, transferMachine, submitEvent calls answer for a Solana-homed machine once the client opts in. Opting in changes what a read can answer, not how you call it. Walkthrough: Onboard a machine on Solana.
Opting in
svm without <"svmEnabled"> does not compile. An svmEnabled client submits events for Solana-homed machines only; send peaq events from a client without svm. @solana/web3.js and @coral-xyz/anchor are optional peer dependencies, loaded only when a machine turns out to live on Solana; an EVM-only client never imports them, and a Solana-homed machine met without them fails with SVM_PACKAGE_MISSING naming the package, except that a read which first has to resolve the home chain (getMachineOwner, getMachineAvailability, getMachineManagementState) throws HOME_CHAIN_UNRESOLVED with homeChainReason: "missing_dependency". The public Solana deployment record is solana-mainnet (SVM_DEPLOYMENTS, resolveSvmDeployment; the constant also carries an internal test record): cluster mainnet-beta, protocol chain ID 5 (SOLANA_PROTOCOL_CHAIN_ID), LayerZero EID 30168, the program IDs from the contracts page and the peering between peaq’s MachineBridgeAdapter and the Solana store PDA. Before any account is decoded the SDK checks the endpoint’s genesis hash against the record, that the programs the read needs are executable, and that the record’s peering is consistent (the Solana peer peaq stores is the adapter’s store account, the peaq peer is a 20-byte address); onboarding reads the live peer account before signing. Program IDs come from the record, never from an IDL’s address field.
Reads
getMachineOwner and getMachineAvailability return a tagged result:
evmOperator is the peaq operator the bond is booked under (the address the owner wallet was registered from). The subscription itself stays on peaq for every home: for a Solana-homed machine read it from getMachineManagementState(machineId).subscription; getMachineSubscription needs a peaq ERC-721 and throws MACHINE_NOT_FOUND for a Solana-homed machine. A location the SDK cannot establish throws ActivationError HOME_CHAIN_UNRESOLVED with homeChainState (reserved, in_flight, unknown, conflict, unavailable) and homeChainReason (missing_configuration, missing_dependency, missing_capability, conflicting_evidence). A missing dependency or an unreachable RPC is never reported as a missing machine. Solana reads wait out a rate limit (HTTP 429) and a server behind the slot a read needs (JSON-RPC -32016) and retry, up to five attempts, never for a send; a server that stays behind is named in the final READ_FAILED.
Onboarding
Terminal-first, the same flow as the Python SDK in camelCase withbigint amounts: the Solana owner pays the bond on Solana, in PEAQ or USDC, through the subscription terminal, and peaq books it. The link push back to peaq is delivered by peaq’s Trust Validator node (the node), with no messaging fee. Both rails run on production. The phases, in order:
The example is the script that onboarded the proven JavaScript machines, given in full on the guide’s JavaScript tab (the collapsed block under its run command, to copy): one loop over
getMachineActivationState that does whatever nextStep names until complete, journaling every write. Its two write calls, a terminal stage and a native one:
computeUnitLimit is the plan’s suggestion, plan.native.suggestedComputeUnitLimit: preview again with it and submit with it (see The mint below). getSigner resolves the owner’s signer once: getSolanaOnboardingSignerRequirements(inputs, plan, "native_onboarding", { candidateAddress }), then solanaSignerFromWallet(name, passphrase, true, undefined, required.chainId) and validateSolanaOnboardingSigner(inputs, plan, "native_onboarding", signer). The client needs both halves configured: the peaq-mainnet deployment (the default) and svm: { rpcUrl, commitment: "finalized" }; nothing on peaq is signed after the registration, so a client that only onboards can carry a throwaway privateKey.
- Registration.
registerSolanaOperatorspends peaq gas only (about 0.01 PEAQ; 98,688 and 105,432 gas measured) and waits for the node to mirror the binding. A wallet already bound to the signer isaction: "reconciled", and nothing is sent. A wallet bound to another address is refusedOPERATOR_BOUND_ELSEWHERE.getSolanaOperatorRegistration(wallet, { peaqOperator? })reads the state keyless:unbound,bound,bound_elsewhereormirroring. Confirmation is theOperatorAddressBoundevent in a finalized block, never receipt status. - The quote.
quoteSolanaActivation(identity, { tier, payIn, wallet })is keyless and refuses in the program’s order (OPERATOR_NOT_REGISTERED,MACHINE_ALREADY_ACTIVE,REQUEST_ALREADY_OPEN,INSUFFICIENT_BALANCE…). It returnsbond,maxIn(the suggested escrow, the bond plus the slippage cushion; on USDC the swap’s estimate plus the cushion),walletBalanceandpriceAgeSecs. - The priority price.
computeUnitPriceMicroLamportsdefaults to0non the terminal phases; the plan takes it inpreviewMachineActivation’s budget. Pass10_000n, as the script does: a write without priority can be dropped by Solana’s public endpoint under load. The SDK re-sends a write that was lost on its way. While the write’s receipt wait sees the signature unknown and the blockhash still valid, the SDK sends the same signed bytes again every 2 s, at most 40 times. The same bytes carry the same signature, so the cluster processes the write at most once and nothing can be spent twice. The bytes stay in this process’s memory: a rerun in a new process re-sends nothing and reconciles the journal row. A re-send’s errors are ignored; the receipt decides. A mint that never lands at all is still proven dead by the recovery (mayResubmit) and minted again. At 10,000, with the mint’s limit sized from its simulation, the whole onboarding pays about 4,900 lamports of priority fees on PEAQ and about 7,900 on USDC. request. EscrowsmaxInAmountin the pay-in token and freezes the bond; on PEAQ the escrow must cover the bond (ESCROW_BELOW_BOND). The rents (2,169,160 lamports for the request, 1,488,440 for its escrow account and, on the machine’s first request, 1,071,880 for itsSubscriptionTerminal) count againstmaxNativeRentLamports. A request the node does not credit within its hour endsstatus: "exited"withexit: "REQUEST_EXPIRED". The node cancels that request once it can, returning the escrow and the request’s rents, or the owner cancels it withcancel_request. A rerun after the request was cancelled (by the owner, or by the node once it expired) or refunded opens a new request at the next nonce: the request phase reads the machine’s terminal record first, and a request that is gone, with its nonce no longer open and no live subscription, is spent, not taken for a live one. A request closed after the mint stays done. On a request already cancelled or refunded,cancel_requestrun alone is refused withREQUEST_CLOSED; a cancel this journal recorded still reconcilescomplete.finalise. The request decides the path: in PEAQ to the terminal’s vault, or on USDC a swap that buys exactly the bond through the provision pool, against the record’s finalise lookup table. The swap is quoted by simulating the exact instruction; the cap sent is that cost plus the slippage, never above the escrow.result.settlement(SwapSettlementQuote:simulatedInAmount,maxInAmount,escrowAmount,slippageBps,lookupTable,lockInTable) says how a USDC settlement was priced.previewSolanaSettlementruns the same preparation keyless;verifySolanaFinaliseTablechecks the table alone. A request already cancelled or refunded is refusedREQUEST_CLOSEDbefore signing, byfinaliseand bypreviewSolanaSettlement. After a finalise there is no cancel: if peaq refuses the bond, the refund comes back in PEAQ on both rails (exit: "ACTIVATION_REFUNDED", withresult.refund).- Results. Each terminal call returns
statuscomplete,pending(unresolved,advice) orexited(a namedexit, with the way out inadvice). A signed send whose outcome is unknown throwsPendingTransactionError(TRANSACTION_PENDING); its row is journaled, and a rerun reconciles it. Each confirmation carriessendCount({ sends, resendErrors }): the sends this process made for the write; it isundefinedfor a row this process did not send. REQUEST_CLOSED. A phase run alone on a request that was cancelled or refunded is refused with this code before anything is signed: thecreditandbondwaits,finaliseandpreviewSolanaSettlement, andcancel_request. It replacesREQUEST_NOT_COMMITTED,STATE_MISMATCHorREQUEST_NOT_CANCELLABLEin that situation. Nothing is left to wait for, settle or cancel; the request phase opens a new request at the next nonce. A refund still ends thebondwait asACTIVATION_REFUNDED.- The mint.
native_onboardingmints against the bonded request withinputs(owner, controller, manufacturer, machine type, credential subject, the DID lists, the two native ceilings, optionalevmOperatorassertion) and theplanfrompreviewMachineActivation({ chain: "solana", inputs, computeUnitLimit, computeUnitPriceMicroLamports }).plan.native.suggestedComputeUnitLimitis the value to pass ascomputeUnitLimit: the plan’s simulated units × 1.3, rounded up to the next 1,000, at least 50,000 and at most the cluster maximum. On production a mint used 99,009 compute units on 2026-10-08. A mint whose receipt failed withComputationalBudgetExceeded(reasoncompute_budget_exceeded), with theMachineandMachineStateaccounts absent, is minted again by the rerun, like a mint that never landed: the reconciliation marks itfailedWithoutEffect, andnoEffectcovers both cases. Every other failed mint staysfailed. - The link push. The SDK reads the route from the chain before every push.
quoteSolanaLinkPush(machineId, { payer })is keyless:transportistrust_validator(production:nativeFeeLamports0n,computeUnitLimit120,000,pushAccountRentLamports1,005,840) orlayerzero;statusalready_pushedmeans nothing is left to send. On the node’s routemaxLinkPushFeeLamportsis not needed; on a LayerZero route a push without it throwsValidationErroron that field before signing. Refused before signing:TV_OUTBOX_MISSING,TV_INBOUND_REFUSED,SVM_FEE_EXCEEDED(a fee or the push account’s rent over its ceiling), andINSUFFICIENT_BALANCEwhen the owner cannot pay the push and keep its own rent-exempt minimum (650,240 lamports for a plain wallet). The confirmation carriestransport,tvNonceandsequence. - Complete. When peaq’s
MachineBridgeAdapter.lastAppliedMirrorPushSeqfor the machine reaches the push’s sequence:getMachineActivationState(machineId, { chain: "solana", inputs, records })readsnextStep.phase === "complete".tvRelayslists the pushes that went over the node (signature,dstEid,nonce,applied);messageslists LayerZero messages and is empty on the node’s route. - Journal and recovery. The three Solana rows are handed to
onTransactionSubmittedbefore broadcast, the registration row right after its broadcast; a write that stays unconfirmed throwsPendingTransactionError(TRANSACTION_PENDING, the row on.submitted) and is reconciled on the next run. The process that signed it may re-send the same signed bytes while the write can still land; a rerun in a new process re-sends nothing. Store each row as oneserializeSolanaOnboardingAttempt(row, client.deployment)line and read them back withdecodeSolanaOnboardingAttempt. Pass every row to status reads and the native phases. After an earlier request was cancelled, refunded or closed (observations.terminal.requestState), the request phase reads the machine’s terminal record first and opens a new request at the next nonce. The script’srequestRowsalso leaves that request’s rows (nonce at or belowobservations.terminal.terminal.lastNonce) out of the new call’srecords. - What ran.
getSolanaOnboardingHistory(machineId, { timeoutSeconds })rebuilds the onboarding from the chains alone, keyless:rows(step,actorowner/operator/node/layerzero/other, slot or block, cost to its payer, the owner’s own change whoever paid inownerLamportsDeltaandownerTokenDeltas, explorerlinks) andtotalsper payer (the owner’s is its net change, refunds from others’ transactions included). A cancel the node sends reads actornode. Sources it could not read are named inunread; a rerun reads them. Right after a run the public endpoints are busy: the script allows 600 s.confirmSolanaOnboardingReceipts(records)reads back the registration’s and the terminal writes’ receipts for a cost report after a resume. - Migrating from 0.10.x. The reservation-first API (
SvmOnboardingInputwithfunding, thereservationandsubscriptionphases,serializeSvmOnboardingProgress) is gone; onboard with the phases above.
Management
Requests carryingchain: "solana" take the native path through the entry points they already have; the client never reroutes an EVM call because Solana is configured.
A write is preview, decide, write:
previewMachineAction({ chain: "solana", action, machineId, signer, ..., accepted: { maxFeeLamports, maxRentLamports } }), then transferMachine({ chain: "solana", preview, request, rpc, native: { computeUnitLimit, computeUnitPriceMicroLamports }, commitment, getSigner }). The write-capable rpc is yours to supply; the client’s Solana connection is read-only. approveMachine and safeTransferMachine have no Solana semantics: once the home-chain reads resolve the machine to Solana they throw UnsupportedError SVM_APPROVAL_UNSUPPORTED / SVM_SAFE_TRANSFER_UNSUPPORTED; setMachineApprovalForAll carries no machine ID and throws SVM_APPROVAL_FOR_ALL_UNSUPPORTED only when called with chain: "solana" (the Python code for the first two is SOLANA_OPERATION_UNSUPPORTED; Python’s set_machine_approval_for_all keeps its EVM behaviour). Results report confirmed, unconfirmed, blocked or failed; unconfirmed is not a failure, reconcile it. setMachineEvmOperator reports sync separately (pending until peaq’s lastAppliedMirrorPushSeq for source chain 5 equals that exact source sequence and the latest source snapshot still describes the current state; a synchronized result carries reusedExistingPush: true, the SDK never sends the message itself); matching operators on both chains prove nothing on their own. DID setters resize the account, so rent moves to or from whoever signed; the preview reports it separately from fees.
Events
submitEvent and batchSubmitEvents write to the Solana EventRegistry program for a Solana-homed machine. They need the SVM-enabled client and two options: getSigner, resolving an OwsSolanaSigner (PeaqosClient.solanaSignerFromWallet(name, passphrase)), and commitment ("confirmed" or "finalized"). Params are SubmitSvmEventParams: machineId (bigint), eventType (0 revenue, 1 activity), value and timestamp (bigint or safe integer), rawData, trustLevel, sourceChainId, sourceTxHash, metadata, currency (smart default for a single event, required per event in a batch). A batch is one Solana transaction; every machine in it must be homed on the same deployment. The timestamp must not exceed the observed cluster time (STATE_MISMATCH otherwise). The first event for a machine also pays rent for its MachineEventLog account; the fee payer is the signer. The result (SvmEventSubmissionResult) carries executionChain: "solana", machineId (bigint), signature, submissionId, slot, confirmationLevel, dataHash, eventIndex and optional computeUnits. onTransactionSubmitted receives a payload-free NativeEventSubmissionAttempt (signature, lastValidBlockHeight, submission ID) before the broadcast. reconcileSvmEventSubmission (complete, failed, expired, unresolved) and rebroadcastSvmEventTransaction are exported, but the first needs the packaged IDL, which the package does not export, and the second needs signed bytes the SDK never returns; check an uncertain attempt’s signature on the cluster instead. Replace only an expired attempt via options.replace. An uncertain wait throws TRANSACTION_PENDING (default timeoutMs 120 s), not PendingTransactionError. Other options: timeoutMs, signal, computeUnitPriceMicroLamports, computeUnitLimit, acceptedCostBounds (maxFeeLamports, maxRentLamports; refused before signing above them). There is no event preview in JS. Walkthrough: Submit events: machines homed on Solana. A confirmed event is not an MCR update; the 2.0 MCR indexes Solana events asynchronously.
MCR API compatibility
The query and monetization clients follow the 2.0 MCR server’s contract for Solana-homed machines.revenueTrend is RevenueTrend | null and averageRevenuePerEvent is number | null (null means not computable, never substitute "stable" or 0; totalRevenue stays non-null), a null or fractional mcr_score throws BAD_RESPONSE, and MonetizationState.signer is string | null because a Solana owner’s key is base58. Optional fields, present only for a machine homed away from peaq: homeChain (protocol chain ordinal, Solana is 5; compare against SOLANA_PROTOCOL_CHAIN_ID, never against 3338 or 30168), ratingUnavailable (any non-empty value means the score is a floor), and on the profile owner (home-chain address format), controller, machine_type, relocating. operator stays an EVM address DID on every home. HTTP, transport and non-JSON failures throw McrApiError with code (see MCR API error codes), serverCode, httpStatus, homeProtocolChainId, retryable (a classification; the transport never retries); response shape and correlation failures throw RuntimeError with code BAD_RESPONSE. Monetization opt-in signed by a Solana owner is implemented (five-line message with home_chain: 5, plain Ed25519 signMessage, body with signer_pubkey). When solanaSigner is set, the SDK reads the machine’s home chain first (a compatibility GET and a profile GET) and refuses a Solana-homed write with MonetizationValidationError SOLANA_MONETIZATION_UNVERIFIED before signing. Without a Solana signer the SDK does not check the home chain and sends the EIP-191 write.
Gas Station
1
Setup 2FA
Call
setupFaucet2FA to enroll the owner.2
Confirm 2FA
Call
confirmFaucet2FA with a TOTP from the authenticator.3
Fund
Call
fundFromGasStation to send gas to a machine wallet.setupFaucet2FA
Enrolls an owner address for 2FA with the Gas Station. Returns a QR code URL (expires after ~2 minutes).
ValidationError on empty args. RuntimeError for INVALID_OWNER_ADDRESS, INVALID_PAYLOAD, QR_GENERATION_FAILED, unexpected envelope, or HTTP failure. See errors.
confirmFaucet2FA
Confirms 2FA enrollment with a fresh TOTP code.
void on successful activation.
Errors: ValidationError on any empty argument. RuntimeError for INVALID_2FA, 2FA_NOT_CONFIGURED, 2FA_LOCKED, unexpected envelope, or transport failure.
fundFromGasStation
Sends gas tokens to a machine wallet. Returns a discriminated union on status.
requestId back in both success and skipped responses. The Python SDK does not include request_id in the response at all: it is a request-side idempotency key only. Do not write code that reads requestId from the response and expects it to work in both SDKs.
Events (Qualify)
Both calls write a peaq-homed machine’s events to the deployment record’sEventRegistry (0xA1e7F1d7B24dAb55Dc92491e6d9B89F6E925Ad1e on peaq-mainnet); batchSubmitEvents sends through the batch precompile (PEAQ_BATCH_PRECOMPILE_ADDRESS), and every batch event names its currency. When the EventRegistry refuses an event, the RuntimeError carries code NOT_OWNER_OR_CONTROLLER, SUBSCRIPTION_NOT_ELIGIBLE, METADATA_TOO_LARGE, INVALID_CURRENCY_SHAPE, FUTURE_TIMESTAMP or MACHINE_NOT_FOUND (ERC721NonexistentToken); InvalidEventType and InvalidTrustLevel keep their Solidity names. On a record without an EventRegistry (agung-2026-08-28) both throw DeploymentConfigError DEPLOYMENT_UNAVAILABLE with missingContracts: ["eventRegistry"] before any RPC or signature. An svmEnabled client submits Solana-homed events only: without getSigner it throws DeploymentConfigError DEPLOYMENT_NOT_CONFIGURED, and for a peaq-homed machine ActivationError CHAIN_MISMATCH.
machineId on SubmitEventParams and MachineEvent is bigint (1024n, not 1024). On an SVM-enabled client the same two calls write a Solana-homed machine’s events to the Solana EventRegistry program instead: see Solana (SVM).
submitEvent
Submits a single event to EventRegistry. Validates and normalizes the payload, then calls the contract. Returns the transaction hash and the computed dataHash.
validateSubmitEventParams below. value is an ISO 4217 minor-unit integer (cents for USD/HKD, whole units for JPY/KRW/VND). The MCR counts revenue only in its 25 supported currencies, listed on Submit events. currency is required on revenue events (^[A-Z0-9]{3,10}$) and must be "" on activity events; the SDK applies a smart default (revenue → "USD", activity → "") when omitted on submitEvent. batchSubmitEvents is strict: every event must carry currency explicitly.
batchSubmitEvents
Submits multiple events atomically through the peaq Batch precompile. All events land in the same transaction: all succeed or all revert.
Non-empty list of event payloads. Each element is validated individually before submission.
validateSubmitEventParams
Non-negative ISO 4217 minor-unit integer. Cents for USD/HKD, whole units for JPY/KRW/VND. Activity events: any non-negative integer or
0.Revenue: 3-10 uppercase alphanumeric (e.g.
"USD", "HKD", "JPY"). Activity: must be "". Omit to apply the SDK smart default (revenue → "USD", activity → ""); batchSubmitEvents requires it explicitly.Arbitrary bytes stored on-chain alongside the event. Use empty bytes when no metadata is needed.
void. Throws ValidationError on any invariant violation, and a native TypeError when value is not an integer (fractional or wrong type).
computeDataHash
keccak256 hash as 0x + 64 hex characters.
checkOperationalLimits
Current rate-tracking state for the machine. Pass
null if you are not tracking window state. EventTracker is { machineId: bigint; count: number; windowStart: number }.void. Throws ValueCapExceeded or RateLimitExceeded on limit violation.
Queries
All three read the deployment’s MCR server (mcr.peaq.xyz for peaq-mainnet); on agung-2026-08-28, which has no MCR, they throw DeploymentConfigError DEPLOYMENT_UNAVAILABLE before any request. An unknown machine is McrApiError NOT_FOUND (an untyped 404). Machine DIDs are did:peaq:<decimal machine id>, operator DIDs stay did:peaq:0x<address>, machineId in results is bigint. A malformed or non-canonical machine_id, or a response about a different machine or operator, throws RuntimeError BAD_RESPONSE. See API reference.
Read-only helpers backed by the off-chain MCR API server. Each function validates the DID, issues a single GET, and returns a frozen, shape-checked response. All three accept an optional GetJsonOptions with timeoutMs (default 30 000 ms) and a caller AbortSignal.
queryMcr
Fetches the Machine Credit Rating for a machine DID. See GET /mcr/{did}.
Frozen object with camelCase fields:
did, machineId, mcrScore (number, 0–100), mcr ("AAA" | "AA" | "A" | "BBB" | "BB" | "B" | "NR" | "Provisioned"), mcrDegraded (boolean: true when revenue for a peaq-homed machine was converted at a stale stored FX rate; always false for a Solana-homed machine), bondStatus ("bonded" | "unbonded"), negativeFlag (boolean: true when the machine has been flagged for negative behaviour; consumers should down-rank or alert independently of the numeric score), eventCount, revenueEventCount, activityEventCount, revenueTrend ("up" | "stable" | "down" | "insufficient", or null when not computable, never substitute "stable"), totalRevenue (USD cents, an integer sum of the revenue events worth at least 1,000 USD cents; divide by 100 for display; never null), averageRevenuePerEvent (USD cents, rounded to 2 decimals; null when not computable), lastUpdated (unix seconds or null). Two optional fields appear only for a machine homed away from peaq: homeChain (protocol chain ordinal, Solana is 5; compare with SOLANA_PROTOCOL_CHAIN_ID) and ratingUnavailable (any non-empty value means the score is a floor, not a measurement). Details: MCR API compatibility.mcr_score: 0 while a machine is still Provisioned or has rating NR. A null or fractional mcr_score throws BAD_RESPONSE, and ratingUnavailable carries the reason an unscored machine has no rating.
queryMachine
Fetches the full machine profile (NFT Metadata JSON v1.0) for a DID. The SDK strictly validates the response against MachineProfileResponse and throws BAD_RESPONSE for any missing or malformed required field. See GET /machine/{did}.
Frozen, strictly-validated machine profile. Top-level fields:
schema_version (string) and name (string). The peaqos sub-object always carries machine_id, did, operator, mcr, mcr_score, bond_status, negative_flag, event_count, data_visibility, and documentation_url. The MCR API returns data_visibility: "private" for every machine and no event rows or partner data. data_api appears when the machine’s DID carries a peaq-data-api service endpoint. event_data, partner_data, and partner_data_error stay optional in the type; the MCR API does not return them. A machine homed away from peaq adds optional owner (home-chain address format, base58 on Solana, never an EVM address), controller, machine_type, relocating, home_chain and rating_unavailable (the profile’s spelling of the pair under MCR API compatibility); operator stays an EVM address DID. The SDK throws BAD_RESPONSE if the server returns anything that fails the schema guard. See GET /machine/{did} for full field semantics.queryOperatorMachines
Fetches the fleet of machines managed by a proxy operator. Each machine summary carries its DID, machine ID, score, rating tier, and negativeFlag; the response also includes pagination metadata. See GET /operator/{did}/machines.
Frozen object with
operatorDid, a frozen machines array, and a pagination object. Each machine entry exposes did, machineId, mcrScore (number, 0–100; a null or fractional score throws BAD_RESPONSE), mcr rating, and negativeFlag (boolean: true when the machine has been flagged for negative behaviour). pagination carries offset, limit, and total (all non-negative integers).Verify
Experimental, beta: the Verify surface lives on its own subpath,@peaqos/peaq-os-sdk/verify, is not exported from the package root (there is no client.verify), and may change without a major version bump. It ships two things: an API read client and three pure chip preflight functions. It has no attester, submission, anchoring or hardware code.
VerifyReadClient
Reads one machine’s record from the Verify API. The API is authoritative: the client validates the response shape and returns it frozen; it does not read the registry, an RPC or a DID service, and never compares the result with local preflight evidence.
HTTPS origin of the Verify API, no path, query or credentials:
https://mcr.peaq.xyz on peaq mainnet. There is no default.A
fetch-compatible function. Pass the global fetch; construction never calls it.From
registryMachineId(123n): a bigint in 1..2^256-1. A DID, an address or 0 throws VerifyValidationError before any request.Frozen.
machineId, machineDid (did:peaq:<decimal>), homeChain ({ kind: "evm", chainId } or { kind: "solana", genesisHash }), didController and operator ({ kind, address } in the home chain’s native kind), and verification.kyb.status / verification.chip.status, each "unverified" | "verified" | "expired" | "revoked" | "lapsed". lapsed is new in 0.13.0: before it, a response carrying lapsed threw VerifyProtocolError (unknown-status), and code that switches on the status exhaustively needs a lapsed branch. No aggregate flag.machineId, machineDid, didController.address and operator.address are typed wrapper objects ({ kind, value }), not plain strings: read .value for the string (machineDid.value, didController.address.value, operator.address.value) and machineId.value for the bigint.GET /v1/verify/machines/{machineId} with a five-second deadline and a 4096-byte response ceiling, rejects redirects, sends no credentials and keeps no cache. Nothing retries; a 429 is reported, not retried.
Chip preflight
Three functions that run on the machine and turn a challenge plus the chip’s leaf certificate and two signatures into the canonicalpeaq.verify.chip-evidence/1 document. They perform no I/O: no chip access, no network, no key, no file. A platform adapter reads the certificate from the OPTIGA Trust M Express object 0xE0E0 and asks key 0xE0F0 to sign; the DID controller’s wallet signs the controller message. Fixed profile infineon-optiga-trust-m-express-ca306/1, trust bundle infineon-optiga-trust-m-express-ca306-roots/1; no other chip, root or curve. EVM controller and chain ID only.
ChipPreflightEvidence exposes the fixed identifiers (protocol, profile, evidenceSchema, trustBundle), revocationStatus: "not_evaluated" (the SDK checked no revocation list), evidenceHash, chipRef and toEvidenceBytes(). Every stage rechecks now < expiresAt <= now + 300 and the certificate validity, so run all three right after the challenge. A VerifyFreshnessError needs a new challenge, a new ChipPreflightContext and all three stages again; after any other failure, correct the rejected input and call the failed stage again.
Preflight success means the material is locally valid. It does not consume the challenge, does not submit anything, and does not set
chip.status to verified: the onboarding service submits the bytes with POST /v1/verify/chip/evidence, and chip.status reads verified once peaq records the chip attestation. The full flow is in Verify a chip, end to end.Error classes
See errors for the full hierarchy and the 20-code faucet table.Type exports
All exported types
All exported types
Constants
Tiers and activation defaults
Tiers and activation defaults
Event types & trust levels
Event types & trust levels
Chain IDs & LayerZero endpoints
Chain IDs & LayerZero endpoints
Solana and MCR API
Solana and MCR API
Wallet import chains, key types & passphrase env
Wallet import chains, key types & passphrase env
IMPORT_CHAIN_* is the union behind the ImportChain type alias used by importWallet. KEY_TYPE_* matches the KeyType field on WalletInfo.OWS signing error codes
OWS signing error codes
PeaqosClient.fromWallet(..., owsSigning: true). The matching OwsSigningErrorCode type is the union of all five string-literal codes.
