Skip to content

Commit

Permalink
add contacts actions to applesauce-actions
Browse files Browse the repository at this point in the history
  • Loading branch information
hzrd149 committed Mar 11, 2025
1 parent 0dca3fb commit 75d7254
Show file tree
Hide file tree
Showing 19 changed files with 500 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/eight-emus-give.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"applesauce-actions": minor
---

Add contact list actions
5 changes: 5 additions & 0 deletions .changeset/sixty-kangaroos-begin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"applesauce-factory": minor
---

Add `EventFactory.sign` method for signing events
21 changes: 21 additions & 0 deletions packages/actions/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2024 hzrd149

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
56 changes: 56 additions & 0 deletions packages/actions/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"name": "applesauce-actions",
"version": "0.11.0",
"description": "A package for performing common nostr actions",
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"watch:build": "tsc --watch > /dev/null",
"test": "vitest run --passWithNoTests",
"watch:test": "vitest"
},
"keywords": [
"nostr",
"applesauce"
],
"author": "hzrd149",
"license": "MIT",
"files": [
"dist"
],
"exports": {
".": {
"import": "./dist/index.js",
"require": "./dist/index.js",
"types": "./dist/index.d.ts"
},
"./actions": {
"import": "./dist/actions/index.js",
"require": "./dist/actions/index.js",
"types": "./dist/actions/index.d.ts"
},
"./actions/*": {
"import": "./dist/actions/*.js",
"require": "./dist/actions/*.js",
"types": "./dist/actions/*.d.ts"
}
},
"dependencies": {
"applesauce-core": "^0.11.0",
"applesauce-factory": "^0.11.0",
"nostr-tools": "^2.10.4"
},
"devDependencies": {
"@types/debug": "^4.1.12",
"applesauce-signers": "workspace:^0.11.0",
"nanoid": "^5.0.9",
"typescript": "^5.7.3",
"vitest": "^3.0.5"
},
"funding": {
"type": "lightning",
"url": "lightning:nostrudel@geyser.fund"
}
}
46 changes: 46 additions & 0 deletions packages/actions/src/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Applesauce Actions

`applesauce-actions` is a package that contains common "actions" that a nostr app might take

## Install

```sh
npm install applesauce-actions
```

## Example

```js
import { EventStore } from "applesauce-core";
import { EventFactory } from "applesauce-factory";
import { SimpleSigner } from "applesauce-signers";
import { ActionHub, Actions } from "applesauce-actions";

const user = new SimpleSigner();
const events = new EventStore();
const factory = new EventFactory({ signer: user });

const publish = async (event) => {
// manually handle publishing
await customRelayPool.publish(event);
};

// create a new action hub that combines the event store, factory, and publish
const hub = new ActionHub(events, factory, publish);

// load events into event store
const contacts = await loadUserContactEvent(user);

// add the kind 3 event to the store
// The following FollowUser action will fail if it cant find the contacts event
events.add(contacts);

// modify the contacts event by running an action
await hub.run(
Actions.FollowUser,
"3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d",
"wss://pyramid.fiatjaf.com/",
);

// This will update the contacts event, and call publish with the new signed event
```
42 changes: 42 additions & 0 deletions packages/actions/src/__tests__/fake-user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { unixNow } from "applesauce-core/helpers";
import { SimpleSigner } from "applesauce-signers/signers/simple-signer";
import { nanoid } from "nanoid";
import type { NostrEvent } from "nostr-tools";
import { finalizeEvent, getPublicKey, kinds } from "nostr-tools";

export class FakeUser extends SimpleSigner {
pubkey = getPublicKey(this.key);

event(data?: Partial<NostrEvent>): NostrEvent {
return finalizeEvent(
{
kind: data?.kind ?? kinds.ShortTextNote,
content: data?.content || "",
created_at: data?.created_at ?? unixNow(),
tags: data?.tags || [],
},
this.key,
);
}

note(content = "Hello World", extra?: Partial<NostrEvent>) {
return this.event({ kind: kinds.ShortTextNote, content, ...extra });
}

profile(profile: any, extra?: Partial<NostrEvent>) {
return this.event({ kind: kinds.Metadata, content: JSON.stringify({ ...profile }), ...extra });
}

contacts(pubkeys: string[] = []) {
return this.event({ kind: kinds.Contacts, tags: pubkeys.map((p) => ["p", p]) });
}

list(tags: string[][] = [], extra?: Partial<NostrEvent>) {
return this.event({
kind: kinds.Bookmarksets,
content: "",
tags: [["d", nanoid()], ...tags],
...extra,
});
}
}
80 changes: 80 additions & 0 deletions packages/actions/src/action-hub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { EventStore } from "applesauce-core";
import { EventFactory } from "applesauce-factory";
import { NostrEvent } from "nostr-tools";

import { FollowUser } from "./actions/contacts.js";

/**
* A callback used to tell the upstream app to publish an event
* @param label a label describing what
*/
export type PublishMethod = (label: string, event: NostrEvent, explicitRelays?: string[]) => Promise<void>;

/** The context that is passed to actions for them to use to preform actions */
export type ActionContext = {
/** The event store to load events from */
events: EventStore;
/** The pubkey of the signer in the event factory */
self: string;
/** The event factory used to build and modify events */
factory: EventFactory;
/** A method used to publish final events to relays */
publish: PublishMethod;
};

/** An action that can be run in a context to preform an action */
export type Action<T extends unknown = unknown> = (ctx: ActionContext) => Promise<T>;

export type ActionConstructor<Args extends Array<any>, T extends unknown = unknown> = (...args: Args) => Action<T>;

/** The main class that runs actions */
export class ActionHub {
constructor(
public events: EventStore,
public factory: EventFactory,
public publish: PublishMethod,
) {
/** The the context observable to get the pubkey */
// this.context = defer(() => {
// if (!this.factory.context.signer) throw new Error("Missing signer");
// return from(this.factory.context.signer.getPublicKey());
// }).pipe(map((self) => ({ self, events: this.events, factory: this.factory, publish: this.publish })));
}

// log = new Subject<{ label: string; args: Array<any>; result: any }>();

protected context: ActionContext | undefined = undefined;
async getContext() {
if (this.context) return this.context;
else {
if (!this.factory.context.signer) throw new Error("Missing signer");
const self = await this.factory.context.signer.getPublicKey();
this.context = { self, events: this.events, factory: this.factory, publish: this.publish };
return this.context;
}
}

async run<Args extends Array<any>, T extends unknown = unknown>(
// label: string,
Action: ActionConstructor<Args, T>,
...args: Args
): Promise<T> {
const action = Action(...args);

const ctx = await this.getContext();
return await action(ctx);

// const log = { label, args, result };
// this.log.next(log);

// return await result;
}

// helper methods
follow(pubkey: string) {
return this.run(FollowUser, pubkey);
}
unfollow(pubkey: string) {
return this.run(FollowUser, pubkey);
}
}
74 changes: 74 additions & 0 deletions packages/actions/src/actions/__tests__/contacts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { describe, it, expect, beforeEach, vitest } from "vitest";
import { FakeUser } from "../../__tests__/fake-user.js";
import { EventFactory } from "applesauce-factory";
import { EventStore } from "applesauce-core";
import { ActionHub } from "../../action-hub.js";
import { FollowUser, NewContacts, UnfollowUser } from "../contacts.js";

const user = new FakeUser();

let events: EventStore;
let factory: EventFactory;
let publish: () => Promise<void>;
let hub: ActionHub;
beforeEach(() => {
events = new EventStore();
factory = new EventFactory({ signer: user });
publish = vitest.fn().mockResolvedValue(undefined);
hub = new ActionHub(events, factory, publish);
});

describe("FollowUser", () => {
it("should throw an error if contacts does not exist", async () => {
// don't add any events to the store
await expect(hub.run(FollowUser, user.pubkey)).rejects.toThrow();

expect(publish).not.toHaveBeenCalled();
});

it('should publish an event with a new "p" tag', async () => {
events.add(user.contacts());

await hub.run(FollowUser, user.pubkey);

expect(publish).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ tags: expect.arrayContaining([["p", user.pubkey]]) }),
);
});
});

describe("UnfollowUser", () => {
it("should throw an error if contacts does not exist", async () => {
// don't add any events to the store
await expect(hub.run(UnfollowUser, user.pubkey)).rejects.toThrow();

expect(publish).not.toHaveBeenCalled();
});

it('should publish an event with a new "p" tag', async () => {
events.add(user.contacts([user.pubkey]));

await hub.run(UnfollowUser, user.pubkey);

expect(publish).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ kind: 3, tags: [] }));
});
});

describe("NewContacts", () => {
it("should throw if contact list already exists", async () => {
events.add(user.contacts([user.pubkey]));
await expect(hub.run(NewContacts, [])).rejects.toThrow();
expect(publish).not.toBeCalled();
});

it("should publish a new contact event with pubkeys", async () => {
await hub.run(NewContacts, [user.pubkey]);

expect(publish).toHaveBeenCalled();
expect(publish).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ kind: 3, tags: expect.arrayContaining([["p", user.pubkey]]) }),
);
});
});
39 changes: 39 additions & 0 deletions packages/actions/src/actions/contacts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { kinds } from "nostr-tools";
import { Action } from "../action-hub.js";
import { addPubkeyTag, removePubkeyTag } from "applesauce-factory/operations/tag";

/** An action that adds a pubkey to a users contacts event */
export function FollowUser(pubkey: string, relay?: string, hidden = false): Action {
return async ({ events, factory, self, publish }) => {
const contacts = events.getReplaceable(kinds.Contacts, self);
if (!contacts) throw new Error("Missing contacts event");

const pointer = { pubkey, relays: relay ? [relay] : undefined };
const operation = addPubkeyTag(pointer);
const draft = await factory.modifyTags(contacts, hidden ? { hidden: operation } : operation);
await publish("Update contacts", await factory.sign(draft));
};
}

/** An action that removes a pubkey from a users contacts event */
export function UnfollowUser(pubkey: string, hidden = false): Action {
return async ({ events, factory, self, publish }) => {
const contacts = events.getReplaceable(kinds.Contacts, self);
if (!contacts) throw new Error("Missing contacts event");

const operation = removePubkeyTag(pubkey);
const draft = await factory.modifyTags(contacts, hidden ? { hidden: operation } : operation);
await publish("Update contacts", await factory.sign(draft));
};
}

/** An action that creates a new kind 3 contacts lists, throws if a contact list already exists */
export function NewContacts(pubkeys?: string[]): Action {
return async ({ events, factory, self, publish }) => {
const contacts = events.getReplaceable(kinds.Contacts, self);
if (contacts) throw new Error("Contact list already exists");

const draft = await factory.process({ kind: kinds.Contacts, tags: pubkeys?.map((p) => ["p", p]) });
await publish("New contact list", await factory.sign(draft));
};
}
1 change: 1 addition & 0 deletions packages/actions/src/actions/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./contacts.js";
2 changes: 2 additions & 0 deletions packages/actions/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from "./action-hub.js";
export * as Actions from "./actions/index.js";
Loading

0 comments on commit 75d7254

Please sign in to comment.