> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cowboy.inc/llms.txt
> Use this file to discover all available pages before exploring further.

# Walkthrough: sell a social metrics product

> Build Social Pulse, an actor that tracks Bluesky follower counts, deploy it on Cloud and submit it to the General Store

By the end of this page you'll have Social Pulse running on Cloud and submitted to the General Store as a free listing. Social Pulse tracks public profiles on Bluesky: ask it to refresh a handle, and it records that account's followers, follows and posts, keeping the last 10 snapshots so a hirer can see the trend.

Every file you write is on this page, and the submission package is on [Package and submit](https://docs.cowboy.inc/sell/package-and-submit.md#the-submission-package). To follow along, [install the CLI](https://docs.cowboy.inc/getting-started/install.md). The steps from deploy onward need a [funded wallet](https://docs.cowboy.inc/build/deploy.md#wallets).

## 1. Shape it

Before writing code, split the product into the parts Cowboy runs:

| Part | Runs in | Here |
| - | - | - |
| Rules and records | The actor | Which handles it tracks, the last 10 snapshots, a rate limit per caller |
| Calls to other services | A runner job | One request to Bluesky's public API per refresh |
| Keys | The secret store | None: Bluesky's public API needs no key |

An actor can't reach the network itself, so it hands each request to a **runner**, a machine that does work for actors, and waits for the answer. [Bring existing code](https://docs.cowboy.inc/sell/bring-existing-code.md) has more on making this split.

## 2. Create the project

```bash theme={"system"}
cowboy init social_pulse --dir social-pulse --env cloud
cd social-pulse
```

```text Output theme={"system"}
Environment: cloud
RPC: https://rpc.cloud.cowboy.inc
✓ Project initialized.
→ Preparing Python environment
✓ Python environment ready · .venv (0.2s)

Yeehaw! Project ready: /path/to/social-pulse
```

`--env cloud` makes Cloud this project's network, so later commands don't need it.

## 3. Write the actor

Replace `actors/social_pulse/main.py` with:

```python theme={"system"}
"""Social Pulse: Bluesky profile metrics, fetched by a runner and kept on chain."""

from cowboy_sdk import HOUR, Actor, JobFailed, limit, public, runner, runtime

PROFILE_URL = "https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile?actor="
MAX_SNAPSHOTS = 10
MAX_HANDLES = 50
MAX_HANDLE_LEN = 253
HANDLE_CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.-"


def clean_handle(value: object) -> str:
    if not isinstance(value, str):
        raise ValueError('send a Bluesky handle, e.g. "bsky.app"')
    handle = value.strip().lstrip("@").lower()
    if not handle or len(handle) > MAX_HANDLE_LEN or "." not in handle:
        raise ValueError('send a Bluesky handle, e.g. "bsky.app"')
    for ch in handle:
        if ch not in HANDLE_CHARS:
            raise ValueError("handle has an invalid character")
    return handle


class SocialPulseActor(Actor):
    @public
    def init(self, payload: bytes | None = None) -> None:
        self.storage["history"] = {}

    @public
    @limit(per_caller=20, every=HOUR, pending=2)
    @runner.continuation(timeout=HOUR)
    async def refresh(self, handle: object) -> object:
        handle = clean_handle(handle)
        history = self.storage["history"]
        if handle not in history and len(history) >= MAX_HANDLES:
            raise ValueError("tracking too many handles")
        try:
            reply = await runner.http(PROFILE_URL + handle, method="GET")
        except JobFailed as failure:
            return {"handle": handle, "error": failure.reason}
        data = reply.data
        if not isinstance(data, dict) or "followersCount" not in data:
            error = data.get("message", "unexpected reply") if isinstance(data, dict) else "unexpected reply"
            return {"handle": handle, "error": str(error)[:200]}
        snapshot = {
            "handle": handle,
            "did": data.get("did"),
            "display_name": data.get("displayName"),
            "followers": data.get("followersCount"),
            "follows": data.get("followsCount"),
            "posts": data.get("postsCount"),
            "at_ms": runtime.get_timestamp_ms(),
        }
        history = self.storage["history"]
        if handle not in history and len(history) >= MAX_HANDLES:
            return {"handle": handle, "error": "tracking too many handles"}
        snapshots = history.get(handle, [])
        snapshots.append(snapshot)
        history[handle] = snapshots[-MAX_SNAPSHOTS:]
        self.storage["history"] = history
        return snapshot

    @public
    def latest(self, handle: object) -> object:
        snapshots = self.storage["history"].get(clean_handle(handle), [])
        return snapshots[-1] if snapshots else None

    @public
    def history(self, handle: object) -> object:
        return self.storage["history"].get(clean_handle(handle), [])

    @public
    def handles(self, _payload: object) -> object:
        return sorted(self.storage["history"].keys())
```

`refresh` does the work. It checks the handle, sends one request to Bluesky through a runner with `await runner.http(...)`, and stores the snapshot when the answer comes back. The other three handlers only read what `refresh` stored.

Three choices here matter once strangers can call it:

* **`@limit(per_caller=20, every=HOUR, pending=2)`** caps how often one caller can refresh. The actor pays for every runner job, so without a limit one caller could spend its balance.
* **`MAX_HANDLES` and `MAX_SNAPSHOTS`** bound how much it stores, because the actor pays rent on its state. `refresh` checks the handle count again when the answer comes back, since other refreshes can finish while it waits.
* **Errors come back as answers.** A failed request, or a handle Bluesky doesn't know, returns `{"handle": ..., "error": ...}` and stores nothing.

[Call models, the web and tools](https://docs.cowboy.inc/developers/submitting-jobs.md#how-an-await-works) explains how an `await` waits for a runner.

## 4. Test it

The tests answer the Bluesky request themselves, so they need no network. Replace `tests/test_social_pulse.py` with:

```python theme={"system"}
import pytest
from cowboy_sdk import codec, mock_host
from cowboy_sdk.testing import SimulatedChain

from actors.social_pulse import main

PROFILE = {
    "did": "did:plc:z72i7hdynmk6r22z27h6tvur",
    "handle": "bsky.app",
    "displayName": "Bluesky",
    "followersCount": 1000,
    "followsCount": 5,
    "postsCount": 700,
}


def deploy() -> tuple[main.SocialPulseActor, SimulatedChain]:
    actor = main.SocialPulseActor()
    chain = SimulatedChain(actor)
    mock_host.seed_actor_owner(mock_host.context()["sender"])
    chain.call(actor.init)
    return actor, chain


def test_refresh_fetches_profile_and_keeps_snapshot() -> None:
    actor, chain = deploy()
    chain.call(actor.refresh, codec.encode("@BSKY.app"))
    job = chain.jobs()[-1]
    assert job["job_type"] == "http"
    assert job["payload"]["args"] == [main.PROFILE_URL + "bsky.app"]
    snap = codec.decode(chain.reply(PROFILE))
    assert snap["followers"] == 1000 and snap["posts"] == 700
    latest = codec.decode(chain.call(actor.latest, codec.encode("bsky.app")))
    assert latest["followers"] == 1000
    assert codec.decode(chain.call(actor.handles)) == ["bsky.app"]


def test_history_keeps_last_n() -> None:
    actor, chain = deploy()
    for i in range(main.MAX_SNAPSHOTS + 3):
        chain.call(actor.refresh, codec.encode("bsky.app"))
        chain.reply(dict(PROFILE, followersCount=i))
    history = codec.decode(chain.call(actor.history, codec.encode("bsky.app")))
    assert len(history) == main.MAX_SNAPSHOTS
    assert history[-1]["followers"] == main.MAX_SNAPSHOTS + 2


def test_api_error_is_returned_not_stored() -> None:
    actor, chain = deploy()
    chain.call(actor.refresh, codec.encode("nobody.invalid"))
    out = codec.decode(chain.reply({"error": "InvalidRequest", "message": "Profile not found"}))
    assert out == {"handle": "nobody.invalid", "error": "Profile not found"}
    # A handler that returns None sends no output.
    assert chain.call(actor.latest, codec.encode("nobody.invalid")) is None


def test_failed_job_is_returned() -> None:
    actor, chain = deploy()
    chain.call(actor.refresh, codec.encode("bsky.app"))
    out = codec.decode(chain.fail("deadline"))
    assert out == {"handle": "bsky.app", "error": "deadline"}


@pytest.mark.parametrize("bad", ["", "no-dot", "a b.com", 42, "x/../y.com"])
def test_bad_handles_are_refused(bad: object) -> None:
    actor, chain = deploy()
    with pytest.raises(Exception):
        chain.call(actor.refresh, codec.encode(bad))
    assert chain.jobs() == []
```

```bash theme={"system"}
cowboy check
cowboy test
```

```text Output theme={"system"}
✓ Checked social_pulse
tests/test_social_pulse.py .........                                     [100%]
============================== 9 passed in 0.09s ===============================
```

`chain.reply(...)` answers the last runner job, and `chain.fail(...)` fails it, so each test can play Bluesky's part.

## 5. Try it on your machine

`cowboy run` runs one handler on your machine. It can't reach Bluesky, so fail the request and see what a caller gets back:

```bash theme={"system"}
cowboy run --handler init
cowboy run --handler refresh --payload-json '"bsky.app"' \
  --stub-job-failure deadline
```

```text Output theme={"system"}
{"error":"deadline","handle":"bsky.app"}
```

The first line is what `refresh` returned. The run also prints the actor's state, which still has an empty `history`.

## 6. Deploy it with web access

On Cloud, an actor's web requests need the `http.fetch` permission, which you ask for at deploy in a manifest. Its `allowlist_domains` names the hosts the actor may reach. Social Pulse needs only Bluesky's public API. Save this as `manifest.json` in the project:

```json theme={"system"}
{"entitlements": [{"id": "http.fetch", "params": {"allowlist_domains": ["public.api.bsky.app"]}}]}
```

You can't change the list after the deploy, and a request to any other host is refused. Then deploy:

```bash theme={"system"}
cowboy deploy social_pulse --manifest-json manifest.json \
  --max-spend-usd 5 --owner-funding-cap-usd 2
```

```text Output theme={"system"}
  🤠 Yeehaw! social_pulse is live on cloud

  Actor    0xc437…035A
  Inspect  cowboy actor inspect social_pulse
```

The deploy moves a little money from your wallet to the actor, so it can pay for its runner jobs. `--max-spend-usd` is the most the deploy may take from your wallet, that money included, and if the deploy would cost more it stops before submitting anything.

When the actor's own balance runs short, your wallet backs it up. `--owner-funding-cap-usd` caps what the actor may draw from your wallet over its life. To have it pay only from its own balance, pass `--no-owner-funding` instead ([Keep it funded](https://docs.cowboy.inc/build/deploy.md#keep-it-funded)).

Both caps are ceilings, not money set aside. What your wallet holds is the real limit: nothing can spend more than its balance, whatever the caps say.

## 7. Take a snapshot

Ask for a refresh, then read the actor's state:

```bash theme={"system"}
cowboy actor call social_pulse --handler refresh --payload-json '"bsky.app"'
```

```text Output theme={"system"}
✓ Transaction submitted
→ Waiting for the receipt (up to 120s)
✓ Transaction executed in block 69436 (1.7s)
```

```bash theme={"system"}
cowboy actor state social_pulse
```

```text Output (abridged) theme={"system"}
{
  "__INITIALIZED__": 1,
  "history": {
    "bsky.app": [
      {
        "at_ms": 1793902945009,
        "did": "did:plc:z72i7hdynmk6r22z27h6tvur",
        "display_name": "Bluesky",
        "followers": 35539489,
        "follows": 40,
        "handle": "bsky.app",
        "posts": 918
      }
    ]
  }
}
```

The request takes a moment. A call reports that it went through, not what the handler returned, so read the result from the state. Reading state is free.

Social Pulse works. The rest of this page lists it.

## 8. Publish the source

Reviewers read the exact source you submit, and hirers can too, so it goes in a public storage volume. Storage commands sign with your wallet's key file, keep working files that include a key able to write to your volumes, and record what each transaction may cost. Make a private folder for those files, outside the project:

```bash theme={"system"}
mkdir -m 700 ~/.cbfs-social-pulse
```

Then create a volume for this version and upload the project's files:

```bash theme={"system"}
cowboy cbfs --env cloud --wallet-key ~/.cowboy/keys/default \
  --state-dir ~/.cbfs-social-pulse \
  --spend-ledger ~/.cbfs-social-pulse/spend.json --spend-limit-wei 1000000000 \
  volume create --name social_pulse_v1 --public
for f in README.md cowboy.toml pyproject.toml manifest.json \
  actors/__init__.py actors/social_pulse/__init__.py \
  actors/social_pulse/main.py tests/test_social_pulse.py; do
  cowboy cbfs --env cloud --wallet-key ~/.cowboy/keys/default \
    --state-dir ~/.cbfs-social-pulse \
    --spend-ledger ~/.cbfs-social-pulse/spend.json --spend-limit-wei 1000000000 \
    put social_pulse_v1 "$f" "$f"
done
```

`--wallet-key` is your wallet's key file, which `cowboy wallet create` keeps at `~/.cowboy/keys/default`. `--spend-limit-wei` caps the fees these storage transactions may pay in total, here 1 CBY, and the ledger file records each one. `volume create` also moves a small storage deposit from your wallet into the volume. [Publish the source](https://docs.cowboy.inc/sell/package-and-submit.md#publish-the-source) explains each flag, and where else a key file can go.

> [!WARNING]
>
> **Uploads to Cloud storage can fail from outside the Cowboy network.** Cloud's storage relays aren't publicly reachable yet, so `put` can time out, or stop with an error that asks for a trusted checkpoint. If it does, stop here and report the error to Cowboy. Don't go on to declare the actor: a declaration against a volume your files never reached lists empty source, and it can't be pointed at other files later.

Then read back the volume's full id and its root, a hash of everything in it. The next steps use both:

```bash theme={"system"}
cowboy volume info --name social_pulse_v1 --env cloud \
  --private-key ~/.cowboy/keys/default | python3 -c 'import json, sys
v = json.load(sys.stdin)
print("volume id: 0x" + v["volume_id"])
print("root:      0x" + bytes(v["commitment"]["manifest_root"]).hex())'
```

```text Output theme={"system"}
volume id: 0x7cd6…e0f0
root:      0xac1d…ee62
```

A root of all zeros means nothing reached the volume, so stop as above. `cowboy volume list --env cloud --private-key ~/.cowboy/keys/default` lists every volume your wallet owns, with its id.

Each version you list gets its own volume, so don't change this one after you submit it. When the listing is submitted, delete `~/.cbfs-social-pulse`: it holds a key that can write to your volumes.

## 9. Declare it in the Store

A **declaration** is the Store's record of your actor: its address, the source behind it, and its terms. Pick a random salt, which makes the declaration's id unique:

```bash theme={"system"}
openssl rand -hex 32
```

Then declare the actor with the salt, the actor address `deploy` printed, your wallet address, and the volume id and root from step 8. `cowboy wallet address --private-key ~/.cowboy/keys/default` prints your wallet address, which goes in `--split`:

```bash theme={"system"}
cowboy store declare --actor <actor address> --salt 0x<salt> \
  --manifest-root 0x<root> --claimed-root 0x<root> \
  --volume-id 0x<volume id> --code-visibility public \
  --term free --split <your address>:10000 \
  --human-hireable --agent-hireable
```

```text Output theme={"system"}
Declaration ID: 0x1546…6f64
Transaction hash: 0xaf61…1ed
```

`--term free` sets the price. `--split` says who gets paid, in hundredths of a percent, so `10000` is all of it to you ([Pricing](https://docs.cowboy.inc/sell/pricing.md#splits)). `--human-hireable` and `--agent-hireable` say that people and other agents can both hire it.

## 10. Let the General Store sell it

A **grant** lets a store sell your declaration. The General Store's id on Cloud is `1`:

```bash theme={"system"}
cowboy store grant --declaration-id 0x<declaration id> --store-id 1 \
  --split <your address>:10000 --lease-epoch-blocks 1800
```

```text Output theme={"system"}
Transaction hash: 0x5d0c…574c
```

`--lease-epoch-blocks` is required, but it matters only for private code ([CIP-33](https://docs.cowboy.inc/cips/cip-33-actor-hiring-and-distribution.md#25-key-leases-private-code-actors)). Check that the grant landed, and note its id:

```bash theme={"system"}
cowboy store get-grant --declaration-id 0x<declaration id> --store-id 1
```

```text Output theme={"system"}
{
  "grant_id": 240,
  "lease_epoch_blocks": 1800,
  "split": [
    {
      "beneficiary": "0xC437…E21A",
      "share_bps": 10000
    }
  ],
  "status": "Active",
  "store_id": 1
}
```

> [!NOTE]
>
> **Coming soon:** `store declare` and `store grant` waiting for their transaction to commit and reporting the result. Until then, check with `cowboy store get-declaration` and `cowboy store get-grant`.

## 11. Submit it

The submission package ties it together: the declaration, the source, the grant, what the actor does, and its price. Save the [complete `submission.json`](https://docs.cowboy.inc/sell/package-and-submit#the-submission-package) from Package and submit in the project and fill in your own ids. [Package and submit](https://docs.cowboy.inc/sell/package-and-submit.md#the-submission-package) explains each field.

```bash theme={"system"}
cowboy store submit --input submission.json --json
```

```text Output theme={"system"}
{"schema":"cowboy-command/v2","command":"store.submit","ok":true,
 "result":{"submission":{"id":"2a02e41c-bef4-43f6-bb5c-3c6a8cf77673",
 "reviewState":"Scanning","publicationState":"Not started"}}}
```

Submitting needs no login: your wallet signs it. Follow its progress with:

```bash theme={"system"}
cowboy store submissions --match-input submission.json
```

```text Output theme={"system"}
Recent submissions: 1
Submission: 2a02e41c-bef4-43f6-bb5c-3c6a8cf77673
state: "Queued"
reviewState: "Queued"
publicationState: "Not started"
exact_matches: ["2a02e41c-bef4-43f6-bb5c-3c6a8cf77673"]
```

`Queued` means the automated checks passed and it's waiting for a person to review it. [Review states](https://docs.cowboy.inc/sell/package-and-submit.md#review-states) lists the rest. Approval lists it in the General Store as a free listing.

## Use an API that needs a key

Most social networks want an API key. The actor stays the same apart from the request: mark where the key goes with `runner.secret`, and the runner fills it in when it makes the call. The key never appears in the actor's code, state or calls, which are all public.

Here is the YouTube version, which puts the key in the URL:

```python theme={"system"}
from cowboy_sdk import HOUR, Actor, JobFailed, limit, public, runner, runtime

CHANNELS_URL = "https://www.googleapis.com/youtube/v3/channels"


class YtPulseActor(Actor):
    @public
    def init(self, payload: bytes | None = None) -> None:
        self.storage["latest"] = {}

    @public
    @limit(per_caller=20, every=HOUR, pending=2)
    @runner.continuation(timeout=HOUR)
    async def refresh(self, handle: object) -> object:
        if not isinstance(handle, str) or not handle.isalnum():
            raise ValueError('send a channel handle without the @, e.g. "YouTube"')
        url = runner.secret(
            "YOUTUBE_API_KEY",
            prefix=CHANNELS_URL + "?part=statistics&forHandle=" + handle + "&key=",
        )
        try:
            reply = await runner.http(url=url, method="GET")
        except JobFailed as failure:
            return {"handle": handle, "error": failure.reason}
        items = reply.data.get("items") if isinstance(reply.data, dict) else None
        if not items:
            return {"handle": handle, "error": "channel not found"}
        stats = items[0]["statistics"]
        snapshot = {
            "handle": handle,
            "subscribers": int(stats.get("subscriberCount", 0)),
            "views": int(stats.get("viewCount", 0)),
            "videos": int(stats.get("videoCount", 0)),
            "at_ms": runtime.get_timestamp_ms(),
        }
        latest = self.storage["latest"]
        latest[handle] = snapshot
        self.storage["latest"] = latest
        return snapshot

    @public
    def latest(self, handle: object) -> object:
        return self.storage["latest"].get(handle)
```

The X API takes its key in a header instead. Only the request changes:

```python theme={"system"}
from cowboy_sdk import HOUR, Actor, JobFailed, limit, public, runner

USER_URL = "https://api.x.com/2/users/by/username/"


class XPulseActor(Actor):
    @public
    @limit(per_caller=20, every=HOUR, pending=2)
    @runner.continuation(timeout=HOUR)
    async def refresh(self, username: object) -> object:
        if not isinstance(username, str) or not username.replace("_", "").isalnum():
            raise ValueError('send an X username without the @, e.g. "XDevelopers"')
        try:
            reply = await runner.http(
                url=USER_URL + username + "?user.fields=public_metrics",
                method="GET",
                headers={
                    "Authorization": runner.secret("X_BEARER_TOKEN", prefix="Bearer ")
                },
            )
        except JobFailed as failure:
            return {"username": username, "error": failure.reason}
        data = reply.data.get("data") if isinstance(reply.data, dict) else None
        if not data:
            return {"username": username, "error": "user not found"}
        metrics = data["public_metrics"]
        snapshot = {
            "username": username,
            "followers": metrics["followers_count"],
            "following": metrics["following_count"],
            "posts": metrics["tweet_count"],
        }
        self.storage[username] = snapshot
        return snapshot
```

To ship either one, add its host to `allowlist_domains` (`www.googleapis.com` or `api.x.com`), deploy, and add the key for the deployed actor. [Call an API with a key](https://docs.cowboy.inc/sell/call-an-api-with-a-secret.md) covers those steps, and whose key a listed actor uses.

## Next

* [Package and submit a listing](https://docs.cowboy.inc/sell/package-and-submit.md)
* [Call an API with a key](https://docs.cowboy.inc/sell/call-an-api-with-a-secret.md)
* [Pricing](https://docs.cowboy.inc/sell/pricing.md)


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