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

# Onboard a Machine

> Onboard a machine to peaq using the JavaScript SDK. Create a machine wallet and DID Document with cryptographic identity and service endpoints.

Onboarding a machine to the **peaq network** can be done in several ways. The most direct one is the **JavaScript SDK**, which creates a **DID Document** for the machine.

Test your implementation on the **agung testnet** before you deploy to peaq mainnet. Onboarding, verification, and data storage are then proven before real value is involved.

## Prerequisites

Before onboarding a machine, you should understand:

* **DID Documents**
  * See: [DID Document](https://docs.peaq.xyz/peaqos/concepts/peaqid.md).

## Instructions

The **JavaScript SDK** provides a developer-friendly way to:

* Create a **DID Document** for a machine.
* Define the **machine's cryptographic identity** using `EcdsaSecp256k1`, `Ed25519`, or `Sr25519` based on the wallet that will be used to create signatures.
* Add **service endpoints** to link ownership and storage solutions.
* Store and retrieve DID-related information from the **peaq blockchain**.

### 1. Installing ethers & peaq js

To get started, install:

* **ethers -** library used for wallet generation and token transfer.
* **peaq network sdk -** generates DID Documents and offers peaq storage.

In your local node environment run:

```bash theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
npm install ethers
npm install @peaq-network/sdk
```

If the install gives you trouble, see the [SDK Installation Guide](https://docs.peaq.xyz/peaqchain/build/getting-started/install-peaq-sdk.md).

### 2. Creating a Machine Wallet

Each machine onboarded to the peaq network needs its own cryptographic identity, so you create a dedicated wallet that represents it. The wallet lets the machine sign data, authenticate itself, and send transactions. peaq is **EVM-compatible**, so key management uses the **ECDSA (Elliptic Curve Digital Signature Algorithm)** scheme and the machine can sign with EVM-standard tools.

The example below shows how to generate a new wallet using the `ethers` npm package:

```javascript JavaScript EVM theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
import { Wallet } from "ethers";

// A simple keyring for the machine wallet
class ECDSAKeyring {
    constructor(privateKey) {
      if (privateKey) {
        this.wallet = new Wallet(privateKey);
      } else {
        this.wallet = Wallet.createRandom(); // generates new key
      }
    }
    getAddress() {
      return this.wallet.address;
    }
    getPrivateKey() {
      return this.wallet.privateKey;
    }
    async signMessage(message) {
      return this.wallet.signMessage(message);
    }
}

async function main(){
    // Connect the device to your application logic here
    
    // Create a new EVM-compatible wallet for the machine
    const machineWallet = new ECDSAKeyring();

    // Retrieve the wallet's public address (used to identify the machine on-chain)
    console.log("Machine Address:", machineWallet.getAddress());

    // Retrieve the private key. Store it in your .env file as MACHINE_PRIVATE_KEY,
    // keep it secure, and never share it.
    console.log("MACHINE_PRIVATE_KEY:", machineWallet.getPrivateKey());
}

main();
```

The `ECDSAKeyring` class wraps an EVM-compatible wallet. It exposes the machine's public address, its private key, and a `signMessage` method used later for signing and authentication.

> [!WARNING]
>
> Never share or expose the machine's private key. Possession of this key allows anyone to impersonate the machine, sign data, and perform transactions on its behalf. Losing the key means losing access and control over the machine's on-chain identity.

### 3. Token Transfer

A machine pays a fee in the network's native token for every write it makes on chain: registering its DID, storing data on chain, or calling a smart contract. That fee, called **gas**, pays for computation and storage and keeps spam off the network. Signing a message is done locally on the device, so it needs no gas.

After creating the wallet, transfer a small amount of the native token from your admin wallet to the machine wallet. The machine can then transact on its own. If you have no tokens, use the [faucet page](https://docs.peaq.xyz/peaqchain/build/getting-started/get-test-tokens.md).

The code below demonstrates how to transfer 1 token from an admin account to the machine's wallet:

```javascript JavaScript EVM theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
import { ethers, Wallet } from "ethers";

// A simple keyring for the machine wallet
class ECDSAKeyring {
    constructor(privateKey) {
      if (privateKey) {
        this.wallet = new Wallet(privateKey);
      } else {
        this.wallet = Wallet.createRandom(); // generates new key
      }
    }
    getAddress() {
      return this.wallet.address;
    }
    getPrivateKey() {
      return this.wallet.privateKey;
    }
    async signMessage(message) {
      return this.wallet.signMessage(message);
    }
}

// Load the admin wallet
async function getAdmin(){
    const provider = new ethers.JsonRpcProvider("https://peaq-agung.api.onfinality.io/public"); // agung endpoint for testnet
    const adminPrivateKey = "0xADMIN_PRIVATE_KEY"; // Replace with admin's secure private key
    return new ethers.Wallet(adminPrivateKey, provider);
}

// Transfer native tokens from admin to machine
async function transferNativeToken(adminWallet, machineWallet) {
    const tx = await adminWallet.sendTransaction({
      to: machineWallet.getAddress(),
      value: ethers.parseEther("1") // transfers 1 token over
    });
  
    console.log("Transaction sent:", tx.hash);
    await tx.wait();
    console.log("Transaction confirmed.");
}

async function main(){	
	const MACHINE_PRIVATE = "0xMACHINE_PRIVATE_KEY"; // Replace with your machine's actual private key
    const machineWallet = new ECDSAKeyring(MACHINE_PRIVATE);
    const adminWallet = await getAdmin();

    await transferNativeToken(adminWallet, machineWallet);
}

main();
```

This example uses the agung testnet RPC endpoint. Switch to the peaq mainnet endpoint when you onboard real machines.

After running this script, your **machine wallet** holds 1 native token and can execute transactions on the peaq network.

### 4. Creating a Machine DID Document

With a funded wallet in place, register a **Decentralized Identifier (DID) Document** for the machine. The DID Document is a verifiable structure that ties the machine’s cryptographic keys to a unique identifier, so the machine can authenticate itself and prove ownership of its data.

The example below registers a DID on the **agung testnet** with the peaq JavaScript SDK. The document contains:

* **Verification Methods -** Public keys that let others verify signatures made by the machine.
* **Service Endpoints -** Metadata such as the machine's admin wallet address or off-chain services.

```javascript JavaScript EVM theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
import { Wallet } from "ethers";
import { Sdk } from "@peaq-network/sdk";

class ECDSAKeyring {
    constructor(privateKey) {
      if (privateKey) {
        this.wallet = new Wallet(privateKey);
      } else {
        this.wallet = Wallet.createRandom(); // generates new key
      }
    }
    getAddress() {
      return this.wallet.address;
    }
    getPrivateKey() {
      return this.wallet.privateKey;
    }
    async signMessage(message) {
      return this.wallet.signMessage(message);
    }
}

// Create a new DID on chain
async function generateDID(machineWallet, adminWallet){
    const HTTPS_BASE_URL = "https://peaq-agung.api.onfinality.io/public"; // agung testnet endpoint

    const sdk = await Sdk.createInstance({
        baseUrl: HTTPS_BASE_URL,
        chainType: Sdk.ChainType.EVM
    });

    const name = "project_name"; // Replace with your project/DePIN specific name
    
    const customFields = {
        verifications: [{
            type: "EcdsaSecp256k1RecoveryMethod2020"
        }],
        services: [
            {
                id: '#admin',
                type: 'admin',
                data: `${adminWallet.getAddress()}`
            }
        ]
    };

    // Create a transaction object to register the DID
    const tx = await sdk.did.create({
        name: name,
        address: machineWallet.getAddress(),
        customDocumentFields: customFields
    });

    // Submit the transaction to the network using the machine’s private key
    const receipt = await Sdk.sendEvmTx({
        tx: tx,
        baseUrl: HTTPS_BASE_URL,
        seed: machineWallet.getPrivateKey()
    });
    
    console.log("DID Document registered with receipt:", receipt);
}

async function main(){	
    const MACHINE_PRIVATE = "0xMACHINE_PRIVATE_KEY"; // Replace with your machine key
    const ADMIN_PRIVATE = "0xADMIN_PRIVATE_KEY"; // Replace with your admin key

    const machineWallet = new ECDSAKeyring(MACHINE_PRIVATE);
    const adminWallet = new ECDSAKeyring(ADMIN_PRIVATE);

    await generateDID(machineWallet, adminWallet);
}

main();
```

The DID Document **links** the machine's address to a verification method derived from its wallet, and records the admin account responsible for it. Because the transaction is sent from the machine's wallet, the network can prove the machine created this identity itself.

For updates, deactivation, and retrieval, see [DID Operations](https://docs.peaq.xyz/peaqchain/sdk-reference/javascript/did-operations.md).

## Putting it all together

The script below runs the complete onboarding flow against the agung testnet:

1. Creating a **machine wallet**.
2. Loading an **administrator wallet** (with native tokens).
3. Transferring **tokens** to the machine wallet.
4. Registering a DID Document that represents the **machine's on-chain identity**.

```javascript JavaScript EVM theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
import { ethers, Wallet } from "ethers";
import { Sdk } from "@peaq-network/sdk";

// Simple keyring class for managing EVM-compatible wallets
class ECDSAKeyring {
    constructor(privateKey) {
        this.wallet = privateKey ? new Wallet(privateKey) : Wallet.createRandom();
    }
    getAddress() {
        return this.wallet.address;
    }
    getPrivateKey() {
        return this.wallet.privateKey;
    }
    async signMessage(message) {
        return this.wallet.signMessage(message);
    }
}

// Load an admin wallet with tokens to fund new machine wallets
async function getAdmin() {
    const provider = new ethers.JsonRpcProvider("https://peaq-agung.api.onfinality.io/public"); // Agung testnet
    const adminPrivateKey = "0xADMIN_PRIVATE_KEY"; // Replace securely
    return new Wallet(adminPrivateKey, provider);
}

// Transfer native tokens (gas) to the machine's wallet
async function transferNativeToken(machineWallet, adminWallet) {
    const tx = await adminWallet.sendTransaction({
        to: machineWallet.getAddress(),
        value: ethers.parseEther("1") // Transfer 1 native token
    });

    console.log("Transaction sent:", tx.hash);
    await tx.wait();
    console.log("Transaction confirmed.");
}

// Register a DID Document on the peaq network for the machine
async function generateDID(machineWallet, adminWallet) {
    const HTTPS_BASE_URL = "https://peaq-agung.api.onfinality.io/public";

    const sdk = await Sdk.createInstance({
        baseUrl: HTTPS_BASE_URL,
        chainType: Sdk.ChainType.EVM
    });

    const name = "project_name"; // Customize per project

    const customFields = {
        verifications: [{
            type: "EcdsaSecp256k1RecoveryMethod2020"
        }],
        services: [{
            id: '#admin',
            type: 'admin',
            data: `${adminWallet.address}`
        }]
    };

    const tx = await sdk.did.create({
        name: name,
        address: machineWallet.getAddress(),
        customDocumentFields: customFields
    });

    const receipt = await Sdk.sendEvmTx({
        tx: tx,
        baseUrl: HTTPS_BASE_URL,
        seed: machineWallet.getPrivateKey()
    });

    console.log("peaq DID EVM receipt:\n", receipt);
}


// Main execution flow
async function main() {
    // 1. Create machine wallet
    const machineWallet = new ECDSAKeyring();

    // Save both values before continuing. The next guides reuse the private key
    // as MACHINE_PRIVATE_KEY, so store it in your .env file and keep it secret.
    console.log("Machine Address:", machineWallet.getAddress());
    console.log("MACHINE_PRIVATE_KEY:", machineWallet.getPrivateKey());

    // 2. Load admin wallet
    const adminWallet = await getAdmin();

    // 3. Transfer tokens to the machine
    await transferNativeToken(machineWallet, adminWallet);

    // 4. Create machine DID Document
    await generateDID(machineWallet, adminWallet);
}

main();
```

## Summary

Your machine now has a cryptographic identity (an EVM wallet), native tokens to pay for gas, and a DID Document that serves as its verifiable on-chain identity. It can take part in a DePIN: validating credentials, authenticating data, and running tasks on its own.

For production:

* Store private keys **securely**, for example in encrypted storage or a secure enclave.
* Do not hardcode secrets into your codebase.
* Use the peaq **mainnet** endpoint instead of the agung testnet.

The next step is to store and retrieve data with [**peaq storage**](https://docs.peaq.xyz/peaqchain/sdk-reference/javascript/storage-operations.md), the on-chain layer machines use to persist information.


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