> ## 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.

# Self-managed onboarding

> Activate a single machine where the owner is the operator. Generate keys, set up 2FA, fund via Gas Station, preview, and activate in one transaction.

One machine that owns itself: the machine's own keypair (The two matched secrets behind a wallet: a public address you can share, and a private key you keep secret that signs actions.) signs the activation, so the machine wallet becomes owner, payer and DID controller. The wallet in your `.env` (`PEAQOS_PRIVATE_KEY`) only enrolls in the Gas Station and requests gas for the machine wallet; it gets no rights over the machine. This guide covers the full flow from environment setup through on-chain (On-chain means written to the shared public ledger every machine agrees on: permanent and readable by anyone. Off-chain means kept on a normal private server instead.) activation under [Economics 2.0](https://docs.peaq.xyz/peaqos/concepts/economics-2-0.md). To home the machine on Solana instead (two wallets, seven stages), follow [Onboard a machine on Solana](https://docs.peaq.xyz/peaqos/guides/onboard-on-solana.md).

<details><summary>Key terms in this guide</summary></details>

## Prerequisites

* Node.js ≥ 22 with `@peaqos/peaq-os-sdk` and `dotenv` (`npm i @peaqos/peaq-os-sdk dotenv`; the examples use top-level `await`, so run them as an ES module), or Python 3.10+ with `peaq-os-sdk` and `python-dotenv` (`pip install peaq-os-sdk python-dotenv`)
* A funded EVM (The Ethereum Virtual Machine: the standard runtime many chains share, so the same 0x... addresses and tools work across all of them. peaq is EVM-compatible.) wallet (An account on the chain, identified by a public address, that holds a machine's funds and approves its actions. Really just a pair of keys, not a place money is stored.) holding the tier bond (PEAQ locked when a machine activates, proving skin in the game. It is priced per tier in USD and converted to PEAQ at the oracle rate, and it is not withdrawable. Bonded means the deposit is in place.) plus gas (The small fee, paid in the chain's token, that every action writing to the ledger costs, like a per-write transaction cost.). The bond is quoted per tier at the daily oracle rate, so preview it before you fund. On peaq, bond and gas come out of the same PEAQ balance.
* Environment variables configured per the [install guide](https://docs.peaq.xyz/peaqos/install.md)

The [onboarding quickstart](https://docs.peaq.xyz/peaqos/guides/onboarding-quickstart.md) does everything on this page with the CLI, for peaq and Solana homes. Flag reference on [CLI: activate](https://docs.peaq.xyz/peaqos/cli.md#peaqos-activate).

## Environment setup

```bash .env theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
# peaq mainnet RPC. See /peaqos/install#public-rpc-endpoints for alternatives
PEAQOS_RPC_URL=https://peaq.api.onfinality.io/public
PEAQOS_PRIVATE_KEY=0x<64-hex-chars>
```

The contract addresses ship inside the SDK's deployment record (`peaq-mainnet` unless `PEAQOS_DEPLOYMENT_ID` names another one), so they are not in `.env`.

The Economics 2.0 contract addresses are not environment variables. You select a deployment record (`peaq-mainnet` or `agung-2026-08-28`) in code and the SDK verifies its addresses against `InfoDesk.peer(role)` on chain.

JS examples load the file via `import "dotenv/config"`. Python's `from_env()` reads from the shell, so export the file first with `set -a && source .env && set +a` or call `load_dotenv()`.

## Full flow

**1. Initialize a client from the environment**

`fromEnv` reads the required variables. Throws `ValidationError` if any is missing.

```typescript JS/TS theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
import "dotenv/config";
import { PeaqosClient, type ActivateMachineParams } from "@peaqos/peaq-os-sdk";

const funder = PeaqosClient.fromEnv();
console.log("Funding wallet:", funder.address);
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
from dotenv import load_dotenv
from peaq_os_sdk import PeaqosClient

load_dotenv()

funder = PeaqosClient.from_env()
print("Funding wallet:", funder.address)
```

**2. Generate a keypair (optional)**

If the machine does not already have a wallet, generate one. Local operation, no chain interaction.

```typescript JS/TS theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
const keypair = PeaqosClient.generateKeypair();
console.log("Address:", keypair.address);
// Store keypair.privateKey securely. It cannot be recovered.
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
address, private_key = PeaqosClient.generate_keypair()
print("Address:", address)
# Store private_key securely. It cannot be recovered.
```

If the machine already has a funded wallet, skip to step 6 and build the machine client with that key (the later steps use `keypair.address` / `keypair.privateKey` in JS and `address` / `private_key` in Python, so assign those names from your existing wallet).

**3. Set up 2FA on the funding wallet**

The Gas Station (A peaq service that hands a brand-new, empty wallet a tiny starting amount of tokens so it can afford its first network fees. Gated by 2FA.) requires 2FA before it funds any address.

```typescript JS/TS theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
const FAUCET_URL = "https://depinstation.peaq.xyz";

const enrollment = await funder.setupFaucet2FA(funder.address, FAUCET_URL);
console.log("OTPAuth URI:", enrollment.otpauthUri);
console.log("QR image:", enrollment.qrImageUrl);
// Scan the QR or paste the URI into your authenticator app. The QR URL expires after roughly 2 minutes.
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
FAUCET_URL = "https://depinstation.peaq.xyz"

enrollment = funder.setup_faucet_2fa(owner_address=funder.address, faucet_base_url=FAUCET_URL)
print("OTPAuth URI:", enrollment["otpauth_uri"])
print("QR image:", enrollment["qr_image_url"])
```

**4. Confirm 2FA**

```typescript JS/TS theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
await funder.confirmFaucet2FA(funder.address, FAUCET_URL, "123456"); // current TOTP code
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
funder.confirm_faucet_2fa(owner_address=funder.address, faucet_base_url=FAUCET_URL, two_factor_code="123456")
```

**5. Fund the machine wallet**

Request initial gas from the Gas Station. The faucet funds the wallet or skips if the balance already suffices. The faucet covers gas, not the bond: top up the bond from any PEAQ-holding address after you have previewed the quote in step 7.

```typescript JS/TS theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
const funding = await funder.fundFromGasStation(
  { ownerAddress: funder.address, targetWalletAddress: keypair.address, chainId: "peaq", twoFactorCode: "654321" },
  FAUCET_URL,
);
console.log(funding.status === "success" ? funding.txHash : funding.currentBalance);
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
result = funder.fund_from_gas_station(
    owner_address=funder.address, target_wallet_address=address, chain_id="peaq",
    two_factor_code="654321", faucet_base_url=FAUCET_URL,
)
print(result["tx_hash"] if result["status"] == "success" else result["current_balance"])
```

**6. Build the machine client**

The machine's own key signs the activation, so the machine becomes owner, payer, and controller.

```typescript JS/TS theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
const machine = new PeaqosClient({
  rpcUrl: process.env.PEAQOS_RPC_URL!,
  privateKey: keypair.privateKey,
  deployment: { deploymentId: "peaq-mainnet" }, // "agung-2026-08-28" for the testnet; peaq-mainnet when omitted
});
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
import os

from peaq_os_sdk import DeploymentConfig

machine = PeaqosClient(
    rpc_url=os.environ["PEAQOS_RPC_URL"],
    private_key=private_key,
    deployment=DeploymentConfig(deployment_id="peaq-mainnet"),  # "agung-2026-08-28" for the testnet; peaq-mainnet when omitted
)
```

**7. Preview the activation**

The preview runs the activation's checks up to the quote (chain, contracts, peers, pause state, price) and reports balance and allowance, without signing or spending. It does not reject a short balance or simulate the activation call; the activation does both before it submits. Use it to see the bond, any voucher credit, and the net PEAQ you must hold.

```typescript JS/TS theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
const params: ActivateMachineParams = {
  controller: keypair.address,
  verificationMethods: [{ id: "#key-1", methodType: "Ed25519VerificationKey2020", controller: keypair.address, publicKeyMultibase: "z6Mk..." }],
  authentication: [0n],
  serviceEndpoints: [
    { id: "#docs", serviceType: "peaq-documentation", serviceEndpoint: "https://example.com/docs" },
    { id: "#data", serviceType: "peaq-data-api", serviceEndpoint: "https://example.com/events" },
  ],
  machineType: "Sensor",
  credentialSubject: "0xdeadbeef",     // your identity anchor bytes; fixes the machine ID together with machineType
  manufacturer: "0x3333333333333333333333333333333333333333",
  tier: 0,                             // 0 Entry, 1 Basic, 2 Pro
};

const preview = await machine.previewMachineActivation(params);
console.log("machine ID", preview.machineId.toString());
console.log("bond", preview.bondAmount, "voucher", preview.voucherCredit, "net", preview.netPeaqAmount);
console.log("balance", preview.balance, "approval needed", preview.approvalRequired);
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
from peaq_os_sdk import ActivateMachineParams, ServiceEndpointInput, VerificationMethodInput

params = ActivateMachineParams(
    controller=address,
    verification_methods=(VerificationMethodInput(id="#key-1", method_type="Ed25519VerificationKey2020", controller=address, public_key_multibase="z6Mk..."),),
    authentication=(0,),
    service_endpoints=(
        ServiceEndpointInput(id="#docs", service_type="peaq-documentation", service_endpoint="https://example.com/docs"),
        ServiceEndpointInput(id="#data", service_type="peaq-data-api", service_endpoint="https://example.com/events"),
    ),
    machine_type="Sensor",
    credential_subject=bytes.fromhex("deadbeef"),  # your identity anchor bytes; fixes the machine ID together with machine_type
    manufacturer="0x3333333333333333333333333333333333333333",
    tier=0,  # 0 Entry, 1 Basic, 2 Pro
)

preview = machine.preview_machine_activation(params)
print("machine ID", preview.machine_id)
print("bond", preview.bond_amount, "voucher", preview.voucher_credit, "net", preview.net_peaq_amount)
print("balance", preview.balance, "approval needed", preview.approval_required)
```

If `balance` is below `netPeaqAmount` plus gas, top up the machine wallet now.

**8. Activate**

One transaction. The SDK approves exactly the net amount to `MachineSubscription` if needed, re-quotes, simulates, submits once, then requires the three receipt events and a matching on-chain state before returning.

```typescript JS/TS theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
const result = await machine.activateMachine(params);
console.log("Activated machine", result.machineId.toString());
console.log("Paid", result.netPeaqAmount, "wei of PEAQ; bonded", result.bondAmount);
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
result = machine.activate_machine(params)
print("Activated machine", result.machine_id)
print("Paid", result.net_peaq_amount, "wei of PEAQ; bonded", result.bond_amount)
```

The machine now has a peaqID (`did:peaq:<machine id>`), its Machine NFT (token ID equals the machine ID), and a tier bond. Confirm with `getMachineActivationState` / `get_machine_activation_state`: `subscription.periodStart != 0` means activated (tier 0 is a valid tier, so never test the tier).

## Error handling

| Error | Cause | Resolution |
| :- | :- | :- |
| `ValidationError: Environment variable PEAQOS_PRIVATE_KEY is required but not set` | Missing environment variable | Check your `.env` and shell export |
| `DeploymentConfigError` `DEPLOYMENT_UNKNOWN` | Typo in the deployment ID | Use `peaq-mainnet` or `agung-2026-08-28` |
| `ActivationError` `PRICE_NOT_AVAILABLE` | The oracle holds no PEAQ price for this chain | Chain-side condition; retry after the trust validator's next daily stamp |
| `ActivationError` `INSUFFICIENT_BALANCE` | Wallet holds less than the net PEAQ bond | Top up the machine wallet with the net bond plus a gas margin and retry; this check does not reserve gas |
| `ActivationError` `CONTRACT_REVERTED` naming `ERC721InvalidSender` | The same `machineType` + `credentialSubject` pair was activated before | Pick a new credential subject; the pair is permanent |
| `PendingTransactionError` `PENDING_TRANSACTION` (Python) / `ActivationError` `RECEIPT_UNAVAILABLE` (JS) | Receipt did not arrive in time | Do not resubmit. Reconcile with `reconcile_activation_transaction` (Python) or re-check `getMachineActivationState` by machine ID (JS) |
| `RuntimeError: Invalid 2FA code` / `ApiError: Invalid 2FA code` | TOTP code expired or mistyped | Wait for a fresh code and retry |
| `RuntimeError: Faucet rate limit exceeded` / `ApiError` | Too many funding requests | Retry after a short interval |

Full code tables on [errors](https://docs.peaq.xyz/peaqos/sdk-reference/errors.md#activation-and-deployment-errors).

## What the machine receives

* **peaqID** `did:peaq:<machine id>` with the DID document you supplied (verification methods, authentication, service endpoints)
* **Machine NFT** in `MachineRegistry`, token ID equal to the machine ID
* **Subscription** on the chosen tier for 365 days, bonded in PEAQ; renew before the 14-day grace and 14-day runoff windows end. See [Economics 2.0](https://docs.peaq.xyz/peaqos/concepts/economics-2-0.md#subscription-lifecycle)
* **Home chain record** on peaq
* **Gas Station** funding (if requested)

Machines onboarded under Tokenomics 1.0: see [legacy machines](https://docs.peaq.xyz/peaqos/concepts/economics-2-0.md#legacy-machines).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.