Documentation Index
Fetch the complete documentation index at: https://docs.peaq.xyz/llms.txt
Use this file to discover all available pages before exploring further.
@peaqos/peaq-os-sdk is the opinionated TypeScript entry point for the Machine Financial Passport flow. Each capability is exposed both as a PeaqosClient instance method and as a standalone function.
Install
- Node.js: ≥ 22
- TypeScript: ≥ 5
- Peer dependency:
viem(>= 2.47.10) - 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
| Variable | Required | Default | Purpose |
|---|---|---|---|
PEAQOS_RPC_URL | Yes | n/a | peaq chain RPC endpoint |
PEAQOS_PRIVATE_KEY | Yes | n/a | Owner private key (0x + 64 hex) |
IDENTITY_REGISTRY_ADDRESS | Yes | n/a | Identity Registry contract |
IDENTITY_STAKING_ADDRESS | Yes | n/a | Identity Staking contract |
EVENT_REGISTRY_ADDRESS | Yes | n/a | Event Registry contract |
MACHINE_NFT_ADDRESS | Yes | n/a | Machine NFT contract (LayerZero ONFT) |
DID_REGISTRY_ADDRESS | Yes | n/a | DID Registry precompile |
BATCH_PRECOMPILE_ADDRESS | Yes | n/a | Batch precompile for multi-call bonding |
MACHINE_ACCOUNT_FACTORY_ADDRESS | No | n/a | MachineAccountFactory. Required only for deploySmartAccount / getSmartAccountAddress. |
MACHINE_NFT_ADAPTER_ADDRESS | No | n/a | MachineNFTAdapter (LayerZero ONFT adapter). Required only for bridgeNft when source === "peaq". |
PEAQOS_MCR_API_URL | No | http://127.0.0.1:8000 | MCR API base URL |
OWS_PASSPHRASE | Wallet ops | — | OWS vault passphrase for create/import/export wallet helpers when no explicit passphrase is passed |
peaq mainnet contracts
Use these addresses for thePEAQOS_*_ADDRESS variables when pointing at peaq mainnet. All contracts are UUPS upgradeable proxies; treat the addresses as the current proxy pointers.
| Variable | Address |
|---|---|
IDENTITY_REGISTRY_ADDRESS | 0xb53Af985765031936311273599389b5B68aC9956 |
IDENTITY_STAKING_ADDRESS | 0x11c05A650704136786253e8685f56879A202b1C7 |
EVENT_REGISTRY_ADDRESS | 0x43c6c12eecAf4fB3F164375A9c44f8a6Efc139b9 |
MACHINE_NFT_ADDRESS | 0x2943F80e9DdB11B9Dd275499C661Df78F5F691F9 |
DID_REGISTRY_ADDRESS | 0x0000000000000000000000000000000000000800 (peaq DID precompile) |
BATCH_PRECOMPILE_ADDRESS | 0x0000000000000000000000000000000000000805 (peaq batch precompile) |
MACHINE_ACCOUNT_FACTORY_ADDRESS | 0x4A808d5A90A2c91739E92C70aF19924e0B3D527f |
MACHINE_NFT_ADAPTER_ADDRESS | 0x9AD5408702EC204441A88589B99ADfC2514AFAE6 |
Client
PeaqosClient
RPC endpoint (non-empty).
0x + 64 hex characters.All six contract addresses.
MCR API URL. Defaults to
DEFAULT_API_URL.Per-tx and rate-limit caps. All-zero disables limits.
PeaqosClient instance. toJSON() and util.inspect output redact the private key ("[REDACTED]").
Other RPC endpoints are available. See Public RPC endpoints.
Errors: ValidationError: missing/invalid rpcUrl, privateKey, or any contract address.
fromEnv
PeaqosClient. All required env vars must be set (see Environment variables).
Errors: ValidationError: any required env var missing or empty.
fromWallet
PeaqosClient from an OWS vault wallet. 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.
Wallet name or UUID in the OWS vault.
Vault passphrase. Pass
undefined to fall back to the OWS_PASSPHRASE env var.Route signing through OWS. Defaults to
true when undefined.Client config without
privateKey (the wallet provides the signer).Optional vault configuration (e.g. custom
vaultPath).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. 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.
| Accessor | Type | Description |
|---|---|---|
address | Address | Checksummed owner address derived from privateKey |
rpcUrl | string | Configured RPC endpoint |
contracts | Readonly<ContractAddresses> | Frozen contract address map |
apiUrl | string | MCR API base URL |
operationalLimits | Readonly<OperationalLimits> | Per-tx + rate-limit caps |
publicClient | PublicClient (viem) | Read-only chain client |
walletClient | WalletClient (viem) | Signer-bound chain client |
Registration
registerMachine
Registers the caller’s own address as a machine. Reads minBond from the IdentityRegistry contract (currently 1 PEAQ) and sends that value with the transaction.
The newly allocated machine ID, decoded from the
Registered event in the transaction receipt.registerFor
Registers a machine on behalf of another address. The caller becomes the proxy operator and supplies the current minBond (read from the IdentityRegistry contract) as msg.value.
Machine EOA. The client’s signing address becomes the operator and pays the bond.
The newly allocated machine ID for the proxied machine.
Gas Station
Setup 2FA
Call
setupFaucet2FA to enroll the owner.Confirm 2FA
Call
confirmFaucet2FA with a TOTP from the authenticator.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).
Owner to enroll (SS58 or hex).
Gas Station base URL.
QR format. Defaults to
"svg".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.
Owner address being confirmed.
Gas Station base URL.
Fresh 6-digit TOTP.
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.
2FA-enrolled owner (SS58 or hex).
Machine EOA to fund.
Faucet-configured chain identifier (e.g.,
"peaq").Current TOTP.
UUID idempotency key. Auto-generated if omitted.
NFT & DID
Machine NFT minting, token-ID lookup, and the two canonical DID attribute writers. The DID writes batch six (machine) or two (proxy) attributes into a single atomicbatchAll transaction via the peaq Batch precompile.
mintNft
Mints a Machine NFT on the MachineNFT contract for a registered, bonded machine. Returns the transaction hash.
Registered machine ID. Must be a positive integer.
Address that will own the minted NFT.
tokenIdOf
Reads the NFT token ID assigned to a registered machine via a view call.
Registered machine ID. Must be a positive integer.
The NFT token ID, or
0 if no NFT has been minted for this machine.writeMachineDIDAttributes
Atomically writes the six canonical Machine DID attributes (machineId, nftTokenId, operator, documentation_url, data_api, data_visibility) to the caller’s DID via a single batched transaction.
Registered machine ID.
NFT token ID assigned to the machine.
Operator DID reference. May be an empty string. ASCII, ≤ 2560 bytes.
Non-empty ASCII URL, ≤ 2560 bytes.
Non-empty ASCII URL for the machine’s data API, ≤ 2560 bytes.
Visibility setting.
writeProxyDIDAttributes
Atomically writes the two canonical Proxy DID attributes (machineId, machines) to the caller’s DID.
The proxy operator’s registered machine ID.
Non-empty list of positive machine IDs managed by this proxy. The JSON-encoded array must be ≤ 2560 bytes.
readAttribute
Reads a single DID attribute directly from the peaq DID precompile. Most consumers should prefer the /machine/{did} API, which composes the full attribute set; this helper is the on-chain escape hatch.
The DID account address whose attribute is being read (typically a machine address, but any DID-bearing EOA works).
Attribute key, e.g.
"machineId", "data_visibility", "machines".{ name: string; value: string; validity: number; created: bigint }. validity is 0 when the attribute has no expiry. Throws RuntimeError if the attribute does not exist on the precompile.encodeAddAttribute
Encodes ABI call data for the DID precompile’s addAttribute(didAccount, name, value, validFor) function. Useful when constructing smart-account executeBatch calls that touch the DID precompile alongside other contracts. writeMachineDIDAttributes and writeProxyDIDAttributes use this helper internally; reach for it directly only when composing custom batch flows.
Address of the DID account being written. On-chain this must equal
msg.sender of the resulting precompile call.Attribute name. ASCII only, ≤ 64 bytes.
Attribute value. ASCII only, ≤ 2560 bytes.
Validity period in blocks.
0 means no expiry. Must be a non-negative integer in the uint32 range.ABI-encoded call data. Throws
ValidationError if any constraint is violated.Smart accounts
ERC-4337 smart accounts deployed via theMachineAccountFactory. Requires the client to be constructed with a machineAccountFactory address (or the MACHINE_ACCOUNT_FACTORY_ADDRESS env var via fromEnv).
deploySmartAccount
Deploys a smart account via MachineAccountFactory.createAccount and returns the deployed address.
EOA that will own the smart account.
Machine EOA the account is scoped to.
Non-negative CREATE2 salt.
getSmartAccountAddress
Read-only equivalent: computes the CREATE2 address for the given (owner, machine, salt) without deploying. Returns the same address deploySmartAccount would produce.
deploySmartAccount. No transaction, no gas.
Bridge
Supported routes: peaq ↔ Base. Additional peaqOS chains are added as peer contracts deploy. See Machine NFT cross-chain portability.
machineNftAdapter address (or MACHINE_NFT_ADAPTER_ADDRESS) when sending from peaq. The SDK’s source / destination literal union expands as peer contracts deploy on new chains.
bridgeNft
Bridges a Machine NFT from source to destination. When source === "base", baseRpcUrl and baseNftAddress are required so the SDK can build a per-call viem client for the Base side.
On the peaq→Base path the SDK runs an ERC-721 approval pre-flight: it checks MachineNFT.getApproved(tokenId) and submits a one-shot approve(adapter, tokenId) if the token isn’t already cleared for the adapter. The Base→peaq path uses burn-and-unlock and needs no approval. Either way, callers don’t handle approvals themselves.
Positive NFT id to bridge.
Origin chain.
Target chain (must differ from
source).Destination-chain recipient.
Raw LayerZero v2
extraOptions bytes. Defaults to "0x" (the contract’s enforced options).Base RPC URL. Required only when
source === "base".MachineNFTBase address on Base. Required only when source === "base".The source-chain transaction hash.
waitForBridgeArrival
Static method that polls the destination chain’s MachineNFT.ownerOf(tokenId) every 10 seconds until a non-zero owner returns or the timeout elapses. No PeaqosClient instance required.
Destination-chain RPC endpoint.
MachineNFT contract address on the destination.The NFT id expected to arrive.
Wait budget in seconds. Defaults to 300 (5 min).
Optional abort signal. When aborted, the poll stops immediately with a
RuntimeError code ABORTED.Events (Qualify)
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, thousandths for BHD). 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.
One transaction hash per input event. All hashes are identical (same batch tx).
validateSubmitEventParams
Machine ID returned by
registerMachine / registerFor.0 revenue, 1 activity.Non-negative ISO 4217 minor-unit integer. Cents for USD/HKD, whole units for JPY/KRW/VND, thousandths for BHD. 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.Unix seconds.
Off-chain payload hashed into
dataHash.0 self-reported, 1 on-chain verifiable, 2 hardware-signed.Originating chain. Use
SUPPORTED_CHAIN_IDS.peaq for local.Cross-chain tx hash when applicable.
Arbitrary bytes stored on-chain alongside the event. Use empty bytes when no metadata is needed.
void. Throws ValidationError on any invariant violation.
computeDataHash
Off-chain payload bytes to hash.
keccak256 hash as 0x + 64 hex characters.
checkOperationalLimits
Machine ID and event value.
Configured
maxValuePerTx, rateLimitMaxEvents, rateLimitWindowSeconds.Current rate-tracking state for the machine. Pass
null if you are not tracking window state. EventTracker is { machineId: number; count: number; windowStart: number }.void. Throws ValueCapExceeded or RateLimitExceeded on limit violation.
Queries
Read-only helpers backed by the off-chain MCR API server (client.apiUrl). 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}.
Machine DID. Must start with
did:peaq:0x.Request budget in ms. Defaults to 30 000.
Caller abort signal. Either signal aborting wins.
Frozen object with camelCase fields:
did, machineId, mcrScore (number, 0–100), mcr ("AAA" | "AA" | "A" | "BBB" | "BB" | "B" | "NR" | "Provisioned"), mcrDegraded (boolean: true when ≥1 scored event used a stale or unavailable FX source), 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"), totalRevenue (whole USD as float, not cents), averageRevenuePerEvent (whole USD as float), lastUpdated (unix seconds or null).The MCR API returns
mcr_score: null while a machine is still Provisioned or has rating NR. The JS SDK coerces this to 0 so mcrScore is always a number.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}.
Machine DID. Must start with
did:peaq:0x.Optional
timeoutMs (default 30 000) and caller signal.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. Visibility-dependent extras: data_api, event_data, partner_data, partner_data_error. 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.
Operator DID. Must start with
did:peaq:0x.Optional
timeoutMs (default 30 000) and caller signal.Frozen object with
operatorDid, a frozen machines array, and a pagination object. Each machine entry exposes did, machineId, mcrScore (number, 0–100; null coerced to 0), 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).Error classes
See errors for the full hierarchy and the 20-code faucet table.Type exports
All exported types
All exported types
Constants
Event types & trust levels
Event types & trust levels
DID attributes & limits
DID attributes & limits
Chain IDs & LayerZero endpoints
Chain IDs & LayerZero endpoints
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.
