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

# Monetize: Presence heartbeat

> The machine-side heartbeat client: sign and push a presence heartbeat at a configurable interval, and query any machine's presence.

The heartbeat client ships in `@peaqos/peaq-os-sdk` (JS/TS) and `peaq-os-sdk` (Python), under the `monetization` namespace. It talks to the peaqOS heartbeat service; the peaq-hosted instance is `https://heartbeat.peaq.xyz`, and the base URL stays configuration, never a constant.

A machine that has [opted into monetization](https://docs.peaq.xyz/peaqos/sdk-reference/monetization-opt-in.md) reports that it is online by pushing a signed heartbeat (A short signed 'I'm here' message a machine sends out at a regular interval. As long as heartbeats keep arriving, the machine counts as online; if they stop, it's marked offline automatically.) to the heartbeat service at a regular interval. A valid heartbeat keeps the machine **online**; when heartbeats stop, the server marks it offline. The client does not enforce the opt-in state itself: start it only on an opted-in machine (check with `getMonetization` / `get_monetization`), and stop it when the machine opts out.

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

## Push, not poll

The machine is a *client* of the heartbeat service: it pushes a signed heartbeat out. It does not host an endpoint that others poll, and it never serves its own availability.

```mermaid theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
sequenceDiagram
  participant M as Machine (SDK client)
  participant H as Heartbeat service
  loop every intervalMs
    M->>H: POST /api/v1/heartbeats {machineId, publicKey, sentAt, signature}
    H->>H: verify signature, store presence (online for the TTL)
    H-->>M: {accepted, online, lastHeartbeatAt}
  end
```

## The 180-second TTL and the interval bound

A valid heartbeat marks the machine online for a fixed presence TTL of **180 seconds**. Miss that window and the server flips the machine to offline. To stay online, the machine must heartbeat comfortably more often than the TTL, so the client caps the configured interval:

| Constant | Value | Meaning |
| :- | :- | :- |
| Presence TTL | 180 s | Server presence window (`PRESENCE_TTL_MS` in JS, `PRESENCE_TTL_SECONDS` in Python). |
| Heartbeat margin | 60 s | Safety margin absorbing request latency plus one retry (`HEARTBEAT_MARGIN_MS` / `HEARTBEAT_MARGIN_SECONDS`). |
| Max interval | 120 s | The maximum accepted interval, TTL minus margin (`MAX_HEARTBEAT_INTERVAL_MS` / `MAX_HEARTBEAT_INTERVAL_SECONDS`). |

`start` rejects an interval that is zero, negative, or above the maximum. The exact interval within that bound is caller-supplied configuration.

**Offline is server-derived.** The client never self-reports offline. Stopping the client stops heartbeating; the server observes the absence and lets presence lapse. Operator-initiated maintenance is expressed the same way: stop the client.

## Request-signing auth

There is no bearer credential. The server authenticates each heartbeat by verifying the `signature` against the `publicKey` in the payload.

* The machine identity **private key** is held only by your signer implementation. The client passes it a canonical message and receives a hex signature; the client never handles or logs the raw key.
* `publicKey`, `signature`, `machineId`, and `sentAt` are not secret and are safe to log.

The signature covers exactly this canonical message, byte for byte (two lines, LF-joined, no trailing newline):

```text theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
machineId: {machineId}
sentAt: {sentAt}
```

Build it with `buildCanonicalMessage` / `build_canonical_message`, the single place this format is defined.

## Quick start

```ts JavaScript theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
import { HeartbeatClient } from "@peaqos/peaq-os-sdk";
// or: const heartbeat = client.monetization.createHeartbeatClient();

const heartbeat = new HeartbeatClient();

heartbeat.start({
  baseUrl: "https://heartbeat.peaq.xyz",
  intervalMs: 30_000, // 0 < intervalMs <= 120_000
  machineId: "machine-abc-123",
  publicKey: "0x04…",
  signer, // holds the machine identity private key
  onResult: (res) => {
    // res: { accepted, online, lastHeartbeatAt }
    console.log("online:", res.online);
  },
});

// on shutdown or maintenance:
heartbeat.stop();
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
from peaq_os_sdk.monetization import HeartbeatClient, HeartbeatConfig

heartbeat = HeartbeatClient()

heartbeat.start(HeartbeatConfig(
    base_url="https://heartbeat.peaq.xyz",
    interval_seconds=30,  # 0 < interval_seconds <= 120
    machine_id="machine-abc-123",
    public_key="0x04…",
    signer=signer,  # holds the machine identity private key
    on_result=lambda res: print("online:", res.online),
))

# on shutdown or maintenance:
heartbeat.stop()
```

Each tick sends exactly `{ machineId, publicKey, sentAt, signature }` and parses `{ accepted, online, lastHeartbeatAt }`, surfaced through the optional result callback.

## Fire-and-forget

A failed push, whether a network error or an `accepted: false` response, is logged and retried on the next tick. It never throws out of the timer and never blocks the machine's other operations. Every parsed response reaches the result callback, including rejections.

A hung push cannot stall the loop either. In JS/TS the whole tick (signing plus push) is time-bounded to 30 seconds, or the interval if shorter. In Python the bound is per request: the transport's 10-second HTTP timeout, with signing cancelled cooperatively rather than forced. A server that accepts the connection but never responds is timed out, logged, and retried on the next tick like any other failure.

`stop()` is the one exception: it cancels the timer, aborts any in-flight request (including one still signing), and is treated as expected cancellation, not a failure. No error log, no result callback, no retry.

## Presence query

`checkPresence` / `check_presence` is a standalone one-shot query with no scheduler and no signing. Pass exactly one of `machineId` or `publicKey`:

```ts JavaScript theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
import { checkPresence } from "@peaqos/peaq-os-sdk";

const presence = await checkPresence(
  { machineId: "machine-abc-123" },
  { baseUrl: "https://heartbeat.peaq.xyz" },
);
// { online, machineId, publicKey, lastHeartbeatAt }
```

```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark"}}
from peaq_os_sdk.monetization import PresenceCheckRequest, check_presence

presence = check_presence(
    PresenceCheckRequest(machine_id="machine-abc-123"),
    base_url="https://heartbeat.peaq.xyz",
)
# presence.online, .machine_id, .public_key, .last_heartbeat_at
```

When the machine is offline or unknown, `online` is `false` and `publicKey` / `lastHeartbeatAt` are `null`.

## Presence only

The heartbeat payload is a pure presence signal: it carries no status field and no queue depth. Presence is binary under this API: online (a valid heartbeat within 180 seconds) or offline (TTL expired). Utilisation states such as `busy` are not represented, and maintenance is expressed by stopping the client. Do not add extra fields to the payload.

## API summary

| Symbol | Role |
| :- | :- |
| `HeartbeatClient` | `start(config)` / `stop()` presence scheduler. |
| `HeartbeatSigner` | `sign(message)` returning hex; holds the private key. |
| `buildCanonicalMessage` | Byte-for-byte canonical message builder. |
| `HeartbeatTransport` | Wire and HTTP seam; swap it for tests or a custom stack. |
| `checkPresence` | One-shot presence query. |
| `PRESENCE_TTL_MS`, `HEARTBEAT_MARGIN_MS`, `MAX_HEARTBEAT_INTERVAL_MS` | Interval bounds. |

## Related

* [Monetize function](https://docs.peaq.xyz/peaqos/functions/monetize.md): where the heartbeat fits in the flow
* [Provisioning SDK reference](https://docs.peaq.xyz/peaqos/sdk-reference/provisioning.md): provision the provider node first
* [Monetization opt-in API](https://docs.peaq.xyz/peaqos/api-reference/put-machine-monetization.md)


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