> For the complete documentation index, see [llms.txt](https://docs.xyb.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.xyb.co/xyb-platform-1/xyb-ledger/integrate-with-xyb-ledger/set-up-transaction-workflows/automating-ledger-instructions.md).

# Automating Ledger Instructions

Ledger instructions enable businesses to automate complex workflows such as payments, fund transfers, and account adjustments. This guide provides comprehensive documentation on automating the creation of ledger instructions, for integrating client applications with the ledger via **Kafka** and **HTTPS**.

***

### **What Are Ledger Instructions?**

Ledger instructions are structured commands that initiate operations in the ledger. Each instruction may contain multiple activities, such as:

* **Debiting or Crediting Wallets**
* **Adjusting Balances**
* **Creating Movements and Postings**

#### **Key Components of an Instruction**

1. **Instruction ID**: A unique identifier for tracking and auditing the operation.
2. **Activities**: A list of actions specifying wallets, amounts, and types (debit/credit).
3. **Metadata**: Optional key-value pairs for categorization or business logic.

***

### **Why Automate Ledger Instructions?**

1. **Efficiency**: Automate repetitive financial operations, reducing manual effort.
2. **Accuracy**: Minimize errors by standardizing instruction creation.
3. **Real-Time Processing**: Enable real-time instruction execution via Kafka or HTTPS.
4. **Scalability**: Handle high volumes of transactions with seamless integration.

***

### **Setting Up Automation**

#### **Integration Options**

1. **Kafka**: Asynchronous, event-driven communication.
2. **HTTPS**: Synchronous, REST-based communication.

***

#### **Kafka Integration for Automated Instructions**

**1. Producing Instructions**

Use Kafka producers to send ledger instructions as events.

**Reusable Code Sample (Python):**

```python
from kafka import KafkaProducer
import json

producer = KafkaProducer(
    bootstrap_servers='kafka-broker:9092',
    value_serializer=lambda v: json.dumps(v).encode('utf-8')
)

# Example: Creating a ledger instruction
instruction_event = {
    "instruction_id": "instruction-001",
    "activities": [
        {
            "debit_wallet": "/group/customers/customer123/default/USD",
            "credit_wallet": "/chart/company/revenue/default/USD",
            "amount": 150.00
        }
    ],
    "metadata": {
        "transaction_type": "payment",
        "customer_id": "customer123"
    }
}

producer.send('ledger.instructions', value=instruction_event)
print("Instruction sent successfully!")
```

***

**2. Consuming Instruction Responses**

Listen for ledger responses to confirm instruction processing.

**Code Sample (Python):**

```python
from kafka import KafkaConsumer
import json

consumer = KafkaConsumer(
    'ledger.responses',
    bootstrap_servers='kafka-broker:9092',
    value_deserializer=lambda m: json.loads(m.decode('utf-8'))
)

for message in consumer:
    print(f"Ledger response received: {message.value}")
```

***

#### **HTTPS Integration for Automated Instructions**

**1. Sending Instructions**

Use the `/api/v1/instruction/` endpoint to send instructions synchronously.

**Code Sample (Python):**

```python
import requests

url = "https://ledger.example.com/api/v1/instruction/"
headers = {
    "Authorization": "Bearer <API_KEY>",
    "Content-Type": "application/json"
}

instruction_payload = {
    "instruction_id": "instruction-001",
    "activities": [
        {
            "debit_wallet": "/group/customers/customer123/default/USD",
            "credit_wallet": "/chart/company/revenue/default/USD",
            "amount": 150.00
        }
    ],
    "metadata": {
        "transaction_type": "payment",
        "customer_id": "customer123"
    }
}

response = requests.post(url, json=instruction_payload, headers=headers)

if response.status_code == 200:
    print("Instruction sent successfully!")
else:
    print(f"Error: {response.status_code}, {response.json()}")
```

***

**2. Retrieving Instruction Status**

Use the `/api/v1/instruction/{id}` endpoint to check the status of an instruction.

**Reusable Code Sample (Python):**

```python
instruction_id = "instruction-001"
url = f"https://ledger.example.com/api/v1/instruction/{instruction_id}"
headers = {
    "Authorization": "Bearer <API_KEY>",
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    print(f"Instruction Status: {response.json()}")
else:
    print(f"Error: {response.status_code}, {response.json()}")
```

***

#### **Use Cases for Automated Instructions**

**1. Payment Processing**

**Scenario**: Automate customer payments by debiting their wallet and crediting the company revenue account.\
**Integration Example (HTTPS)**:

```python
instruction_payload = {
    "instruction_id": "payment-12345",
    "activities": [
        {
            "debit_wallet": "/group/customers/customer456/default/USD",
            "credit_wallet": "/chart/company/revenue/default/USD",
            "amount": 200.00
        }
    ]
}
```

***

**2. Bulk Transfers**

**Scenario**: Process multiple fund transfers for payroll or vendor payments using a single instruction.\
**Integration Example (Kafka)**:

```python
instruction_event = {
    "instruction_id": "bulk-transfer-001",
    "activities": [
        {
            "debit_wallet": "/chart/company/payroll/default/USD",
            "credit_wallet": "/group/employees/employee123/default/USD",
            "amount": 1500.00
        },
        {
            "debit_wallet": "/chart/company/payroll/default/USD",
            "credit_wallet": "/group/employees/employee456/default/USD",
            "amount": 2000.00
        }
    ]
}
```

***

**3. Refund Processing**

**Scenario**: Automate refunds by reversing payments through ledger instructions.\
**Integration Example (HTTPS)**:

```python
instruction_payload = {
    "instruction_id": "refund-98765",
    "activities": [
        {
            "debit_wallet": "/chart/company/revenue/default/USD",
            "credit_wallet": "/group/customers/customer789/default/USD",
            "amount": 50.00
        }
    ]
}
```

***

### **Best Practices for Automated Instructions**

1. **Unique Instruction IDs**:
   * Ensure every instruction has a unique ID for traceability.
2. **Monitor Responses**:
   * Use Kafka consumers or HTTPS status checks to confirm processing.
3. **Use Metadata Effectively**:
   * Include metadata for categorization and integration with business logic.
4. **Retry Logic**:
   * Implement retries for failed requests or message deliveries.

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.xyb.co/xyb-platform-1/xyb-ledger/integrate-with-xyb-ledger/set-up-transaction-workflows/automating-ledger-instructions.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
