### Install Lit and @lit-labs/context
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/basic-usage-lit.md
This command installs the Lit library and the @lit-labs/context package, which are necessary for building web components and managing context within a Lit application.
```bash
cd ui
npm install lit @lit-labs/context
```
--------------------------------
### Build and Test Basic hApp (Bash)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/integration-guide.md
Builds the Holochain application to ensure it compiles successfully before integrating hREA. It verifies that the DNA file is created in the workdir.
```bash
# From your project root, build the happ
npm run build:happ # Or bun run build:happ, etc.
# If successful, you'll see your DNA file created
ls dnas/my_dna/workdir/
# Should show my_dna.dna
```
--------------------------------
### HTML Structure for hREA Lit Example
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/basic-usage-lit.md
Sets up the basic HTML structure for a web application integrating with hREA using Lit components. It includes the necessary meta tags, links to stylesheets, and script imports for custom elements like `client-provider` and `hrea-test`.
```html
hREA Lit Example
hREA Lit Integration
```
--------------------------------
### Download hREA DNA via package.json Script (JSON)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/integration-guide.md
Adds a script to the root `package.json` to automatically download the hREA DNA using `curl` during the `postinstall` phase. This ensures the `hrea.dna` file is present in the `workdir/` if it doesn't already exist.
```json
{
"scripts": {
"postinstall": "npm run download-hrea",
// other scripts...
"download-hrea": "[ ! -f \"workdir/hrea.dna\" ] && curl -L --output workdir/hrea.dna https://github.com/h-REA/hREA/releases/download/happ-0.3.3-beta/hrea.dna; exit 0"
}
}
```
--------------------------------
### Create Scaffolded Holochain Web App
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/index.md
This command scaffolds a new Holochain web application using the `hc-scaffold` tool. It requires navigating to your projects directory first. The process involves interactive prompts for UI framework, app name, Holonix environment, package manager, and initial DNA configuration.
```bash
# Navigate to your projects directory
cd ~/your-projects-directory
# Create a scaffolded Holochain web app
nix run "github:holochain/holochain?rev=0a9b89382186834273c3734e5659f7c009139265#hc-scaffold" web-app
```
--------------------------------
### Add UI Dependencies (JSON)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/integration-guide.md
Adds essential dependencies to the UI's `package.json` for communicating with the hREA DNA via GraphQL. Key dependencies include `@apollo/client` for GraphQL client management, `@valueflows/vf-graphql-holochain` for schema creation, and `graphql`.
```json
{
"dependencies": {
"@apollo/client": "^3.7.0",
"@valueflows/vf-graphql-holochain": "^0.0.4-alpha.4",
"graphql": "^16.6.0"
}
}
```
--------------------------------
### Verify Basic DNA Structure (Bash)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/integration-guide.md
Checks if your Holochain application has a basic DNA structure with at least one zome, which is a prerequisite for compiling and integrating hREA. It verifies the presence of DNA directories and zome directories (integrity/ and coordinator/).
```bash
# Check that you have a basic DNA structure in your app's root directory
ls dnas/
# Should show at least one DNA directory (e.g., my_dna/)
# Check that your DNA has at least one zome
ls dnas/my_dna/zomes/
# Should show integrity/ and coordinator/ directories with zomes
```
--------------------------------
### Response of Available Actions
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/thinking-and-expressing-valueflows.md
This is an example JSON response from the `ListAllActions` query, showing a list of valid IDs that can be used for the `action` field in the `createEconomicEvent` mutation.
```json
{"data":{"actions":[
{"id":"dropoff"},
{"id":"pickup"},
{"id":"consume"},
{"id":"use"},
{"id":"work"},
{"id":"cite"},
{"id":"produce"},
{"id":"accept"},
{"id":"modify"},
{"id":"pass"},
{"id":"fail"},
{"id":"deliver-service"},
{"id":"transfer-all-rights"},
{"id":"transfer-custody"},
{"id":"transfer"},
{"id":"move"},
{"id":"raise"},
{"id":"lower"}
]}}
```
--------------------------------
### GraphQL Query: Get Paginated RecipeProcesses
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Retrieves a paginated list of all RecipeProcesses, allowing for cursor-based pagination.
```GraphQL
query ListRecipeProcesses($first: Int, $after: String) {
recipeProcesses(first: $first, after: $after) {
edges {
node {
id
name
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
}
}
```
--------------------------------
### GraphQL Query: Get Paginated RecipeFlows
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Retrieves a paginated list of all RecipeFlows, allowing for cursor-based pagination.
```GraphQL
query ListRecipeFlows($first: Int, $after: String) {
recipeFlows(first: $first, after: $after) {
edges {
node {
id
action
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
}
}
```
--------------------------------
### Create Economic Event with 'raise' action (Working Example)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/thinking-and-expressing-valueflows.md
A functional GraphQL mutation to create an economic event. This version includes all required fields such as action, provider, receiver, resourceClassifiedAs, resourceQuantity, and hasPointInTime, resolving previous errors.
```graphql
mutation FirstEconomicEvent {
createEconomicEvent(
event: {action: "raise", provider: "uhCAkMrhQvJznARbU6HGnDrdMk-eMbEDE7B8GnBDA66wCv0R4UX6f:uhC0k646zXkQKNvC0vhEkQxW-iGgoILG4-QtrdUyDNdzoCbRkOMXO", receiver: "uhCAkMrhQvJznARbU6HGnDrdMk-eMbEDE7B8GnBDA66wCv0R4UX6f:uhC0k646zXkQKNvC0vhEkQxW-iGgoILG4-QtrdUyDNdzoCbRkOMXO", resourceClassifiedAs: "https://some-schema.com/lettuce", resourceQuantity: {hasNumericalValue: 3}, hasPointInTime: "2022-02-20T01:30:15.01-08:00"}
) {
economicEvent {
id
action {
id
}
resourceClassifiedAs
resourceQuantity {
hasNumericalValue
}
hasPointInTime
}
}
}
```
--------------------------------
### GraphQL Query: Get Paginated RecipeExchanges
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Retrieves a paginated list of all RecipeExchanges, allowing for cursor-based pagination.
```GraphQL
query ListRecipeExchanges($first: Int, $after: String) {
recipeExchanges(first: $first, after: $after) {
edges {
node {
id
name
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
}
}
```
--------------------------------
### Configure hREA DNA in happ.yaml (YAML)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/integration-guide.md
Adds the hREA DNA role to your Holochain application's configuration file (`workdir/happ.yaml`). This step is crucial for the application to recognize and include the hREA DNA.
```yaml
manifest_version: "1"
name: your_app_name
roles:
- name: your_main_dna # Your existing DNA role
dna:
bundled: ../dnas/your_dna/workdir/your_dna.dna
# ... other DNA configuration
# Add the hREA role
- name: hrea
dna:
bundled: ./hrea.dna
```
--------------------------------
### GraphQL Query: Get RecipeExchange by ID
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Retrieves a single RecipeExchange using its unique identifier.
```GraphQL
query GetRecipeExchange($id: ID!) {
recipeExchange(id: $id) {
id
name
recipeClauses {
id
action
}
}
}
```
--------------------------------
### GraphQL Query: Get RecipeProcess by ID
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Retrieves a single RecipeProcess using its unique identifier.
```GraphQL
query GetRecipeProcess($id: ID!) {
recipeProcess(id: $id) {
id
name
hasDuration {
amount
unit
}
}
}
```
--------------------------------
### GraphQL Query: Get RecipeFlow by ID
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Retrieves a single RecipeFlow using its unique identifier.
```GraphQL
query GetRecipeFlow($id: ID!) {
recipeFlow(id: $id) {
id
resourceQuantity {
amount
unit
}
action
}
}
```
--------------------------------
### GraphQL ProductBatch Response and Connection Types
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/product-batch.md
Defines response and connection types for product batch operations. Includes ProductBatchResponse for create/update, and ProductBatchConnection for paginated lists.
```GraphQL
type ProductBatchResponse {
productBatch: ProductBatch!
}
type ProductBatchConnection {
edges: [ProductBatchEdge!]!
pageInfo: PageInfo!
}
type ProductBatchEdge {
node: ProductBatch!
cursor: String!
}
```
--------------------------------
### Create RecipeProcess Input
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Defines the parameters for creating a RecipeProcess, including its name, duration, classification, and optional notes.
```GraphQL
input RecipeProcessCreateParams {
name: String!
hasDuration: IDuration
processClassifiedAs: [URI!]
note: String
}
```
--------------------------------
### GraphQL ProductBatch Queries
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/product-batch.md
Provides GraphQL queries for retrieving product batch data. Includes fetching a single batch by ID and a paginated list of all batches.
```GraphQL
productBatch(id: ID!): ProductBatch
productBatches(first: Int, after: String, last: Int, before: String): ProductBatchConnection
```
--------------------------------
### GraphQL Query: Get Unit by ID
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/measurement.md
Retrieves a specific Unit record using its unique identifier. This query is essential for fetching details of a particular measurement unit.
```GraphQL
type Query {
unit(id: ID!): Unit
}
```
--------------------------------
### GraphQL Query: Get Paginated List of Units
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/measurement.md
Retrieves a paginated list of all Unit records. Supports cursor-based pagination using 'first', 'after', 'last', and 'before' arguments.
```GraphQL
type Query {
units(first: Int, after: String, last: Int, before: String): UnitConnection
}
```
--------------------------------
### GraphQL Process Queries
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/process.md
Provides GraphQL queries for fetching process data. 'process' retrieves a single process by ID, while 'processes' fetches a paginated list of all processes.
```GraphQL
type Query {
process(id: ID!): Process
processes(first: Int, after: String, last: Int, before: String): ProcessConnection
}
```
--------------------------------
### GraphQL Plan Queries
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/plan.md
Provides GraphQL query definitions for fetching 'Plan' data. Includes a query to retrieve a single plan by its ID and a paginated query to fetch a list of all plans.
```graphql
type Query {
plan(id: ID!): Plan
plans(first: Int, after: String, last: Int, before: String): PlanConnection
}
```
--------------------------------
### GraphQL Error Response for myAgent
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/using-myagent.md
This is an example of an error response when the 'myAgent' query is called and no Agent data is associated with the currently authenticated user. It indicates that the user needs to associate an agent.
```json
{
"errors": [
{
"message": "Unexpected error value: { type: \"error\", data: { type: \"ribosome_error\", data: \"Wasm error while working with Ribosome: Guest(\"No Agent data is associated with the currently authenticated user\")\" } }",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"myAgent"
]
}
],
"data": {
"myAgent": null
}
}
```
--------------------------------
### hREA GraphQL Integration with Lit
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/basic-usage-lit.md
Demonstrates a LitElement component that consumes hREA client context and uses Apollo Client to perform GraphQL mutations, such as creating a person agent. It includes state management for loading and results, and a basic UI with buttons to trigger actions.
```typescript
import { LitElement, html, css } from 'lit';
import { customElement, state } from 'lit/decorators.js';
import { ContextConsumer } from '@lit-labs/context';
import { hreaClientContext, type HreaClientContext } from './holochain-client';
import { gql, type ApolloClient } from '@apollo/client/core';
@customElement('hrea-test')
export class HreaTest extends LitElement {
// Setup the context consumer
private consumer = new ContextConsumer(this, {
context: hreaClientContext,
subscribe: true // Re-render when the context value changes
});
@state()
private results: string[] = [];
@state()
private isLoading: boolean = false;
private get hreaClient(): ApolloClient | undefined {
return this.consumer.value?.hreaClient;
}
private async createPerson() {
if (!this.hreaClient) return;
this.isLoading = true;
this.results = [...this.results, "🔧 Creating a person agent..."];
try {
const result = await this.hreaClient.mutate({
mutation: gql`
mutation CreatePerson($person: AgentCreateParams!) {
createPerson(person: $person) {
agent { id, name }
}
}
`,
variables: {
person: {
name: `Person ${Date.now()}`,
note: "Created via Lit example",
},
},
});
const agent = result.data.createPerson.agent;
this.results = [...this.results, `✅ Person created: ${agent.name}`];
} catch (e) {
this.results = [...this.results, `❌ Failed to create person: ${(e as Error).message}`];
} finally {
this.isLoading = false;
}
}
// Add other methods like createOrganization, queryAgents etc. here
// ...
render() {
if (!this.consumer.value) {
return html`
Waiting for HREA client...
`
}
return html`
hREA Basic Example (Lit)
Results:
${this.results.map(r => html`
${r}
`)}
`;
}
static styles = css`
/* Add styles for buttons, results, etc. */
`;
}
```
--------------------------------
### Create RecipeFlow Input
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Defines the parameters required to create a new RecipeFlow. Includes fields for action, quantities, relationships to other entities, and descriptive notes.
```GraphQL
input RecipeFlowCreateParams {
action: ID!
resourceQuantity: IMeasure
effortQuantity: IMeasure
recipeInputOf: ID
recipeOutputOf: ID
recipeClauseOf: ID
recipeReciprocalClauseOf: ID
stage: ID
state: String
instructions: String
note: String
}
```
--------------------------------
### GraphQL Response for CreatePerson
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/using-myagent.md
This is an example of a successful response after calling the 'createPerson' mutation. It includes the 'data' object containing the newly created 'agent' with its 'id' and 'name'. The agent ID is crucial for subsequent operations.
```json
{
"data": {
"createPerson": {
"agent": {
"id": "uhCEkhEPmOsgnVv1HCno3T5XbNPl3g8xOf3HxWUGhykVwjGyHDRGH:uhC0kyzFVhHjoqf2ZvsH6FmNQ16DC4EtjD1OIsFbNwJGMBZyVGV3w",
"name": "Luke Skywalker"
}
}
}
}
```
--------------------------------
### GraphQL PlanCreateParams Input Type
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/plan.md
Defines the input parameters required for creating a new 'Plan'. It includes fields like name, inScopeOf, refinementOf, created, due, and note.
```graphql
input PlanCreateParams {
name: String!
inScopeOf: [ID!]
refinementOf: ID
created: DateTime
due: DateTime
note: String
}
```
--------------------------------
### Create RecipeExchange Input
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Defines the parameters for creating a RecipeExchange, requiring a name and optionally accepting a note.
```GraphQL
input RecipeExchangeCreateParams {
name: String!
note: String
}
```
--------------------------------
### GraphQL Mutation: Create RecipeProcess
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Creates a new RecipeProcess with the provided parameters.
```GraphQL
mutation CreateRecipeProcess($process: RecipeProcessCreateParams!) {
createRecipeProcess(process: $process) {
id
revisionId
}
}
```
--------------------------------
### GraphQL Proposal Queries
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/proposal.md
Provides GraphQL queries for retrieving proposal data. Includes a query for a single proposal by ID and paginated queries for all proposals, offers, and requests.
```GraphQL
query GetProposal($id: ID!) {
proposal(id: $id) {
id
name
created
}
}
query ListProposals($first: Int, $after: String) {
proposals(first: $first, after: $after) {
edges {
node {
id
name
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
query ListOffers($first: Int, $after: String) {
offers(first: $first, after: $after) {
edges {
node {
id
name
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
query ListRequests($first: Int, $after: String) {
requests(first: $first, after: $after) {
edges {
node {
id
name
}
}
pageInfo {
hasNextPage
endCursor
}
}
}
```
--------------------------------
### GraphQL Intent Creation Input
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/intent.md
Defines the input parameters required for creating a new intent. It includes fields for identification, resource details, timing, status, and associated metadata.
```graphql
input IntentCreateParams {
name: String
action: ID!
resourceClassifiedAs: [URI!]
resourceQuantity: IMeasure
effortQuantity: IMeasure
availableQuantity: IMeasure
minimumQuantity: IMeasure
hasBeginning: DateTime
hasEnd: DateTime
hasPointInTime: DateTime
due: DateTime
finished: Boolean
image: URI
imageList: [URI!]
note: String
agreedIn: URI
provider: ID
receiver: ID
inScopeOf: [ID!]
resourceInventoriedAs: ID
publishedIn: [ID!]
resourceConformsTo: ID
inputOf: ID
outputOf: ID
}
```
--------------------------------
### GraphQL Schema: OrganizationCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/agent.md
Defines the parameters for creating a new organization. It includes fields for name, image URI, classification URIs, and a note.
```graphql
input OrganizationCreateParams {
name: String!
image: URI
classifiedAs: [URI!]
note: String
}
```
--------------------------------
### LitElement ClientProvider for Holochain Connection
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/basic-usage-lit.md
This TypeScript code defines a LitElement component named `ClientProvider`. It initializes a connection to Holochain using `HolochainConnection` and provides the established client context to its child components. The component displays connection status messages and renders child slots when successfully connected, otherwise showing a loading or error state.
```typescript
import { LitElement, html, css } from 'lit';
import { customElement, state, property } from 'lit/decorators.js';
import { ContextProvider } from '@lit-labs/context';
import { HolochainConnection, hreaClientContext, type HreaClientContext } from './holochain-client';
@customElement('client-provider')
export class ClientProvider extends LitElement {
// Setup the context provider
private provider = new ContextProvider(this, {context: hreaClientContext});
@state()
private connection: HolochainConnection;
@state()
private statusMessage: string = "Initializing...";
constructor() {
super();
// Create a new HolochainConnection instance, passing a callback
// to update the status message on this component.
this.connection = new HolochainConnection((status: string, error?: any) => {
switch(status) {
case 'connecting-holochain':
this.statusMessage = "Connecting to Holochain...";
break;
case 'initializing-hrea':
this.statusMessage = "Initializing hREA GraphQL schema...";
break;
case 'connected':
this.statusMessage = "Connected!";
// When connected, set the value for the context provider
this.provider.setValue(this.connection.getContext());
break;
case 'error':
this.statusMessage = `Error: ${error?.message || 'Unknown error'}`;
break;
}
});
}
firstUpdated() {
// Start the connection process when the component is first added to the DOM
this.connection.connect();
}
render() {
if (this.connection.status === 'connected') {
// If connected, render the child components that were passed in.
return html``;
} else {
// Otherwise, show a loading/error message.
return html`
${this.statusMessage}
`;
}
}
static styles = css`
/* Add styles for spinner and status messages here */
.status {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 200px;
padding: 40px 20px;
}
.error { color: #ff6b6b; }
/* ... etc ... */
`;
}
```
--------------------------------
### GraphQL Input: ProcessCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/process.md
Specifies the input parameters required for creating a new process, including its name, timestamps, status, and relationships.
```GraphQL
input ProcessCreateParams {
name: String!
hasBeginning: DateTime
hasEnd: DateTime
finished: Boolean
classifiedAs: [URI!]
note: String
inScopeOf: [ID!]
plannedWithin: ID
basedOn: ID
}
```
--------------------------------
### GraphQL ProductBatch Input Types
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/product-batch.md
Defines input types for creating and updating product batches. Includes fields for batch number, expiry date, and production date.
```GraphQL
input ProductBatchCreateParams {
batchNumber: String!
expiryDate: DateTime
productionDate: DateTime
}
input ProductBatchUpdateParams {
revisionId: ID!
batchNumber: String
expiryDate: DateTime
productionDate: DateTime
}
```
--------------------------------
### GraphQL ProductBatch Mutations
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/product-batch.md
Defines GraphQL mutations for managing product batch data. Supports creating, updating, and deleting product batches.
```GraphQL
createProductBatch(productBatch: ProductBatchCreateParams!): ProductBatchResponse
updateProductBatch(productBatch: ProductBatchUpdateParams!): ProductBatchResponse
deleteProductBatch(id: ID!): ProductBatchResponse
```
--------------------------------
### GraphQL Input: AgreementCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/agreement.md
Defines the input parameters required for creating a new agreement, including name, creation timestamp, and an optional note.
```graphql
input AgreementCreateParams {
name: String
created: DateTime
note: String
}
```
--------------------------------
### GraphQL Connection: ProcessConnection
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/process.md
Defines the structure for paginated lists of processes, including edges and page information.
```GraphQL
type ProcessConnection {
edges: [ProcessEdge!]!
pageInfo: PageInfo!
}
```
--------------------------------
### Holochain and hREA Connection Logic (TypeScript)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/basic-usage-lit.md
This TypeScript code defines a class for managing connections to Holochain and the hREA backend using Apollo GraphQL. It includes methods for connecting, handling status updates, and retrieving the client context. Dependencies include Apollo Client core, SchemaLink, and Holochain client libraries.
```typescript
import { ApolloClient, InMemoryCache, type ApolloClientOptions } from "@apollo/client/core";
import { SchemaLink } from "@apollo/client/link/schema";
import type { AppClient } from "@holochain/client";
import { AppWebsocket } from "@holochain/client";
import { createHolochainSchema } from "@valueflows/vf-graphql-holochain";
import { createContext } from '@lit-labs/context';
// This is the data that will be passed down via context
export interface HreaClientContext {
holochainClient: AppClient,
hreaClient: ApolloClient,
}
// Lit context key for the hrea client context
export const hreaClientContext = createContext('hrea-client-context');
/**
* Main class to manage Holochain and hREA connections.
*/
export class HolochainConnection {
public appWebsocket!: AppWebsocket;
public holochainClient!: AppClient;
public hreaClient!: ApolloClient;
public status: 'initializing' | 'connected' | 'error' = 'initializing';
public error?: any;
constructor(private onStatusUpdate: (status: string, error?: any) => void) {}
public async connect() {
try {
this.onStatusUpdate('connecting-holochain');
this.appWebsocket = await AppWebsocket.connect();
this.holochainClient = this.appWebsocket.appClient({
installed_app_id: 'hrea-work-testing',
});
this.onStatusUpdate('initializing-hrea');
const schema = await createHolochainSchema({
holochainClient: this.holochainClient,
dnaRoleName: "hrea",
});
const options: ApolloClientOptions = {
cache: new InMemoryCache(),
link: new SchemaLink({ schema }),
defaultOptions: {
query: { fetchPolicy: "cache-first" },
mutate: { fetchPolicy: "no-cache" },
},
};
this.hreaClient = new ApolloClient(options);
this.status = 'connected';
this.onStatusUpdate('connected');
} catch (e) {
console.error("Error connecting to Holochain and hREA", e);
this.status = 'error';
this.error = e;
this.onStatusUpdate('error', e);
}
}
public getContext(): HreaClientContext {
if (this.status !== 'connected') {
throw new Error("Cannot get context when not connected.");
}
return {
holochainClient: this.holochainClient,
hreaClient: this.hreaClient,
}
}
}
```
--------------------------------
### GraphQL Mutation: Create RecipeExchange
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Creates a new RecipeExchange with the provided parameters.
```GraphQL
mutation CreateRecipeExchange($exchange: RecipeExchangeCreateParams!) {
createRecipeExchange(exchange: $exchange) {
id
revisionId
}
}
```
--------------------------------
### GraphQL Input Type: ClaimCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/claim.md
Specifies the parameters required to create a new Claim, including action, resource classification, quantities, triggering event, due date, creation date, completion status, notes, and agreement reference.
```GraphQL
input ClaimCreateParams {
action: ID!
resourceClassifiedAs: [URI!]
resourceQuantity: IMeasure
effortQuantity: IMeasure
due: DateTime
triggeredBy: ID!
created: DateTime
finished: Boolean
note: String
agreedIn: URI
}
```
--------------------------------
### GraphQL ProcessSpecification Queries
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/process-specification.md
Provides GraphQL queries for retrieving process specifications. Includes a query to fetch a single specification by ID and a paginated query to retrieve a list of all specifications.
```graphql
type Query {
processSpecification(id: ID!): ProcessSpecification
processSpecifications(first: Int, after: String, last: Int, before: String): ProcessSpecificationConnection
}
```
--------------------------------
### Create Economic Event with 'raise' action (Initial Attempt)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/thinking-and-expressing-valueflows.md
This GraphQL mutation attempts to create an economic event with the 'raise' action, provider, and receiver. It serves as an initial step before including all necessary fields to satisfy API constraints.
```graphql
mutation FirstEconomicEvent {
createEconomicEvent(event: {
action: "raise",
provider: "uhCAkMrhQvJznARbU6HGnDrdMk-eMbEDE7B8GnBDA66wCv0R4UX6f:uhC0k646zXkQKNvC0vhEkQxW-iGgoILG4-QtrdUyDNdzoCbRkOMXO",
receiver: "uhCAkMrhQvJznARbU6HGnDrdMk-eMbEDE7B8GnBDA66wCv0R4UX6f:uhC0k646zXkQKNvC0vhEkQxW-iGgoILG4-QtrdUyDNdzoCbRkOMXO"
}) {
economicEvent {
id
}
}
}
```
--------------------------------
### GraphQL SettlementCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/claim.md
Defines the input parameters for creating a new settlement. It includes the claim ID, the event that settles it, resource and effort quantities, and an optional note.
```graphql
input SettlementCreateParams {
settles: ID!
settledBy: ID!
resourceQuantity: IMeasure
effortQuantity: IMeasure
note: String
}
```
--------------------------------
### GraphQL RecipeProcess Type
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Defines the structure of a RecipeProcess, representing a step within a recipe. It includes fields for identifiers, name, duration, classification, notes, images, and relationships to RecipeFlows as inputs and outputs.
```GraphQL
type RecipeProcess {
id: ID!
revisionId: ID!
name: String!
hasDuration: Duration
processClassifiedAs: [URI!]
note: String
image: URI
recipeInputs: [RecipeFlow!]
recipeOutputs: [RecipeFlow!]
}
```
--------------------------------
### RecipeProcessConnection Type
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Defines the structure for paginating RecipeProcesses, including a list of edges and page information.
```GraphQL
type RecipeProcessConnection {
edges: [RecipeProcessEdge!]
pageInfo: PageInfo!
}
```
--------------------------------
### GraphQL ProposalCreateParams Input Type
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/proposal.md
Defines the input parameters required for creating a new proposal, including its name, dates, quantity basis, notes, creation time, and associated intents, recipients, and scopes.
```GraphQL
input ProposalCreateParams {
name: String
hasBeginning: DateTime
hasEnd: DateTime
unitBased: Boolean
note: String
created: DateTime
publishes: [ID!]!
reciprocal: [ID!]
proposedTo: [ID!]
inScopeOf: [ID!]
}
```
--------------------------------
### GraphQL Mutation: Create RecipeFlow
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Creates a new RecipeFlow with the provided parameters.
```GraphQL
mutation CreateRecipeFlow($flow: RecipeFlowCreateParams!) {
createRecipeFlow(flow: $flow) {
id
revisionId
}
}
```
--------------------------------
### GraphQL Proposal Mutations
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/proposal.md
Defines GraphQL mutations for managing proposals. Includes creating, updating, and deleting proposals, specifying the required input parameters for each operation.
```GraphQL
mutation CreateNewProposal($proposal: ProposalCreateParams!) {
createProposal(proposal: $proposal) {
proposal {
id
name
created
}
}
}
mutation UpdateExistingProposal($proposal: ProposalUpdateParams!) {
updateProposal(proposal: $proposal) {
proposal {
id
name
created
}
}
}
mutation RemoveProposal($revisionId: ID!) {
deleteProposal(revisionId: $revisionId)
}
```
--------------------------------
### GraphQL AgentCreateParams Input Type
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/agent.md
Defines the input type 'AgentCreateParams' for creating a new agent. It includes fields for name, image, and note.
```graphql
input AgentCreateParams {
name: String!
image: URI
note: String
}
```
--------------------------------
### GraphQL Input: UnitCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/measurement.md
Input structure for creating a new Unit. Includes fields for label, symbol, OM2 identifier, and classification.
```GraphQL
input UnitCreateParams {
label: String!
symbol: String!
omUnitIdentifier: String!
classifiedAs: [URI!]
}
```
--------------------------------
### GraphQL Input: ProcessSpecificationCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/process-specification.md
Defines the input parameters required for creating a new ProcessSpecification, including name, note, and image.
```graphql
input ProcessSpecificationCreateParams {
name: String!
note: String
image: String
}
```
--------------------------------
### RecipeFlowConnection Type
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/recipe.md
Defines the structure for paginating RecipeFlows, including a list of edges and page information.
```GraphQL
type RecipeFlowConnection {
edges: [RecipeFlowEdge!]
pageInfo: PageInfo!
}
```
--------------------------------
### GraphQL Plan Mutations
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/plan.md
Defines GraphQL mutations for managing 'Plan' data. Includes mutations for creating a new plan, updating an existing plan, and deleting a plan.
```graphql
type Mutation {
createPlan(plan: PlanCreateParams!): PlanResponse
updatePlan(plan: PlanUpdateParams!): PlanResponse
deletePlan(revisionId: ID!): PlanResponse
}
```
--------------------------------
### GraphQL Input: ResourceSpecificationCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/resource-specification.md
Input type for creating a new ResourceSpecification, including fields for name, images, classification, notes, units, and substitutability.
```GraphQL
input ResourceSpecificationCreateParams {
name: String!
image: URI
imageList: [URI!]
resourceClassifiedAs: [URI!]
note: String
defaultUnitOfResource: ID
defaultUnitOfEffort: ID
substitutable: Boolean
}
```
--------------------------------
### GraphQL Query for All Actions
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/action.md
A GraphQL query to retrieve a list of all 'Action' objects available in the system. This query fetches all defined actions.
```GraphQL
query GetAllActions {
actions {
id
label
resourceEffect
onhandEffect
}
}
```
--------------------------------
### GraphQL Queries: Claim and Settlement Retrieval
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/claim.md
Provides GraphQL queries to fetch individual Claims and Settlements by their IDs, and paginated lists of all Claims and Settlements.
```GraphQL
query GetClaim($id: ID!) {
claim(id: $id) {
id
# ... other fields
}
}
query ListClaims($first: Int) {
claims(first: $first) {
# ... fields for pagination and claims
}
}
query GetSettlement($id: ID!) {
settlement(id: $id) {
id
# ... other fields
}
}
query ListSettlements($first: Int) {
settlements(first: $first) {
# ... fields for pagination and settlements
}
}
```
--------------------------------
### GraphQL Agent Queries
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/agent.md
Provides GraphQL queries for retrieving agent information. Includes queries to load the currently authenticated agent ('myAgent'), find an agent by ID ('agent'), list all public agents ('agents'), find an organization by ID ('organization'), list all public organizations ('organizations'), find a person by ID ('person'), and list all public people ('people').
```graphql
type Query {
myAgent: Agent
agent(id: ID!): Agent
agents(first: Int, after: String, last: Int, before: String): AgentConnection
organization(id: ID!): Organization
organizations(first: Int, after: String, last: Int, before: String): OrganizationConnection
person(id: ID!): Person
people(first: Int, after: String, last: Int, before: String): PersonConnection
}
```
--------------------------------
### GraphQL Agreement Queries
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/agreement.md
Provides GraphQL queries for fetching agreement data. The `agreement` query retrieves a single agreement by its ID, while the `agreements` query fetches a paginated list of all agreements.
```graphql
query GetAgreement($id: ID!) {
agreement(id: $id) {
id
name
created
}
}
query ListAgreements($first: Int) {
agreements(first: $first) {
edges {
node {
id
name
}
cursor
}
pageInfo {
hasNextPage
endCursor
}
}
}
```
--------------------------------
### Create Economic Event (Initial)
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/thinking-and-expressing-valueflows.md
This GraphQL mutation attempts to create an economic event. It requires an `action` ID and `provider` and `receiver` agent IDs. Initially, the `action` field is left empty.
```graphql
mutation FirstEconomicEvent {
createEconomicEvent(event: {
action: "",
provider: "uhCAkMrhQvJznARbU6HGnDrdMk-eMbEDE7B8GnBDA66wCv0R4UX6f:uhC0k646zXkQKNvC0vhEkQxW-iGgoILG4-QtrdUyDNdzoCbRkOMXO",
receiver: "uhCAkMrhQvJznARbU6HGnDrdMk-eMbEDE7B8GnBDA66wCv0R4UX6f:uhC0k646zXkQKNvC0vhEkQxW-iGgoILG4-QtrdUyDNdzoCbRkOMXO"
})
}
```
--------------------------------
### GraphQL Plan Type Definition
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/plan.md
Defines the 'Plan' object type in GraphQL, outlining its fields such as id, revisionId, name, created, due, note, and relationships to other types like AccountingScope, AgentConnection, Commitment, Scenario, and Process.
```graphql
type Plan {
id: ID!
revisionId: ID!
name: String!
created: DateTime
due: DateTime
note: String
deletable: Boolean
inScopeOf: [AccountingScope!]
involvedAgents: AgentConnection
independentDemands: [Commitment!]
nonProcessCommitments: [Commitment!]
revision(revisionId: ID!): Plan
meta: RecordMeta!
processes: [Process!]
refinementOf: Scenario
}
```
--------------------------------
### GraphQL Query: Retrieve Paginated List of Economic Resources
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/economic-resource.md
This GraphQL query retrieves a paginated list of 'EconomicResource's. It includes parameters for pagination (first, after, last, before) and demonstrates fetching basic information for each resource in the list.
```GraphQL
query ListEconomicResources($first: Int, $after: String, $last: Int, $before: String) {
economicResources(first: $first, after: $after, last: $last, before: $before) {
edges {
node {
id
name
trackingIdentifier
}
cursor
}
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
}
}
}
```
--------------------------------
### GraphQL ProductBatch Type Definition
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/product-batch.md
Defines the ProductBatch type, representing a lot or batch of a resource. It includes fields like id, revisionId, batchNumber, expiryDate, and productionDate.
```GraphQL
type ProductBatch {
id: ID!
revisionId: ID!
batchNumber: String!
expiryDate: DateTime
productionDate: DateTime
}
```
--------------------------------
### GraphQL Schema: EconomicEventCreateParams Input Type
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/economic-event.md
Specifies the input parameters required for creating a new economic event. It includes details like provider, receiver, action, resource information, quantities, and temporal data.
```graphql
input EconomicEventCreateParams {
provider: ID!
receiver: ID!
action: ID!
resourceInventoriedAs: ID
resourceClassifiedAs: [URI!]
resourceQuantity: IMeasure
effortQuantity: IMeasure
hasBeginning: DateTime
hasEnd: DateTime
hasPointInTime: DateTime
note: String
agreedIn: URI
triggeredBy: ID
toResourceInventoriedAs: ID
satisfies: [ID!]
fulfills: [ID!]
}
```
--------------------------------
### GraphQL ProposalConnection Type
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/proposal.md
Defines the structure for paginated lists of proposals, including edges and page information.
```GraphQL
type ProposalConnection {
edges: [ProposalEdge!]!
pageInfo: PageInfo!
}
```
--------------------------------
### GraphQL Input: EconomicResourceCreateParams
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/economic-resource.md
This GraphQL input type defines the parameters required to create a new 'EconomicResource'. It includes fields for name, tracking identifier, image, and containment information.
```GraphQL
input EconomicResourceCreateParams {
name: String
trackingIdentifier: String
image: URI
imageList: [URI!]
containedIn: ID
note: String
}
```
--------------------------------
### GraphQL Connection: ResourceSpecificationConnection
Source: https://github.com/h-rea/graphql-developer-docs/blob/main/reference/graphql-api-reference/resource-specification.md
Connection type for paginating lists of ResourceSpecifications, including edges and page information.
```GraphQL
type ResourceSpecificationConnection {
edges: [ResourceSpecificationEdge!]!
pageInfo: PageInfo!
}
```