# API Reference

**Version:** 2.6.6

Other plugins can listen to bank deposits and withdrawals, put items into a player's bank and open bank windows. All classes are in the bank jar (`KyuubiSoftBank-2.6.6.jar`, package `com.hytale.bank`).

---

## Setup

- Compile against the bank jar (`compileOnly`); do not shade it.
- Declare the bank as a dependency in your `manifest.json` so it loads first, for example `"OptionalDependencies": { "kyuubisoft:bank": "*" }`.
- When the bank is optional for your plugin, keep every bank class reference in a separate class that you only load after checking that the bank is present.

```java
import com.hytale.bank.BankPlugin;

BankPlugin bank = BankPlugin.getInstance(); // set when the bank plugin is created
```

`BankPlugin` also offers `getBankService()`, `getBankConfig()`, `getDatabase()` and `getPlayerData(...)`, described below.

---

## Events

The bank has its own small event bus, `BankEventBus`. Its events are **not** posted on Hytale's event registry; register on the bus.

### BankDepositEvent

| Getter | Type | Description |
|--------|------|-------------|
| `getPlayerRef()` | `PlayerRef` | The bank owner |
| `getItemId()` | `String` | Item ID, for example `Ingredient_Bar_Gold` |
| `getQuantity()` | `int` | Number of items that went in |
| `getPage()` | `int` | `0` for moves in the bank window, `-1` for `addItemOrDrop` |

### BankWithdrawEvent

| Getter | Type | Description |
|--------|------|-------------|
| `getPlayerRef()` | `PlayerRef` | The bank owner |
| `getItemId()` | `String` | Item ID |
| `getQuantity()` | `int` | Number of items that came out |
| `getPage()` | `int` | Always `0` in 2.6.6 |

### When the events fire

| Change | Event |
|--------|-------|
| `BankService.addItemOrDrop(...)` stores an item | `BankDepositEvent` with page `-1` |
| A move between the player's inventory and the bank that the game's container system performs | `BankDepositEvent` or `BankWithdrawEvent` |
| A click or drag-and-drop transfer handled by the 2.6.6 bank window | **none** (the move is written to the history only) |
| Coin deposits, coin payouts, transfers | none |
| `/ksbank give`, admin changes, moves while an admin looks into someone else's bank | none |

Because most moves in the 2.6.6 window are click transfers, do not rely on the events for a complete record; read the history database instead (see below).

### Listening

```java
import com.hytale.bank.event.BankEventBus;
import com.hytale.bank.event.BankDepositEvent;
import com.hytale.bank.event.BankWithdrawEvent;

BankEventBus.getInstance().register(BankDepositEvent.class, event -> {
    String player = event.getPlayerRef().getUsername();
    LOGGER.info(player + " stored " + event.getQuantity() + "x " + event.getItemId());
});

BankEventBus.getInstance().register(BankWithdrawEvent.class, event -> {
    // react to a withdrawal
});
```

Listeners run synchronously on the thread that changed the bank. An exception in a listener is logged and does not stop the other listeners. Keep listeners short.

### BankEventBus

| Method | Description |
|--------|-------------|
| `static BankEventBus getInstance()` | The single bus |
| `<T> void register(Class<T> type, Consumer<T> listener)` | Adds a listener for exactly this event class |
| `<T> void fire(T event)` | Calls the listeners of the event's class (used by the bank) |
| `void clear()` | Removes every listener; the bank calls it when it shuts down |

There is no unregister method; register once during your plugin's setup.

---

## BankService

```java
BankService service = BankPlugin.getInstance().getBankService();
```

### `boolean addItemOrDrop(PlayerRef playerRef, ItemStack stack)`

Puts an item into the player's bank, for example as a reward.

1. The item goes into the first **empty** slot of the player's unlocked pages (it is not added to existing stacks); pages that cannot be read are skipped. Only the item ID and the quantity are kept; durability and metadata of the stack are not.
2. On success the bank file is saved, a `DEPOSIT` line is written to the history and a `BankDepositEvent` (page `-1`) is fired. Returns `true`.
3. When the bank is full, the item is dropped at the player's feet (if the player is in a world). Returns `false`.

Notes:

- It takes a `PlayerRef`, so it is meant for online players. When the player has no bank file yet it returns `false` without dropping anything.
- It always uses the normal bank, also with world banking on.
- **While the player has the bank window open,** the window is saved and closed first and the item is added afterwards on the window's world thread. The method then returns `true` at once, meaning "queued". A full bank still drops the item at the player's feet, but the caller does not learn about it; an error is written to the log.

```java
ItemStack reward = new ItemStack("Ingredient_Bar_Gold", 10);
boolean stored = BankPlugin.getInstance().getBankService().addItemOrDrop(playerRef, reward);
playerRef.sendMessage(Message.raw(stored
    ? "Your reward is in your bank."
    : "Your bank is full, the reward was dropped at your feet."));
```

### Opening bank windows

| Method | Description |
|--------|-------------|
| `boolean openBank(Player player, PlayerRef playerRef, int page)` | Opens the player's own bank window; `page` starts at `0`. With world banking on, the bank of the player's current world group opens. |
| `boolean openBankFor(Player viewer, PlayerBankData data, int page)` | Opens the bank `data` for another player (the admin view). |

Call both on the player's world thread. They return `false` when the window could not be opened.

### Pages

| Method | Description |
|--------|-------------|
| `boolean upgrade(PlayerBankData data, Player player)` | Buys the next page with the default price list, like `/ksbank upgrade`, and sends the chat answer |
| `boolean upgrade(PlayerBankData data, Player player, String provider)` | The same with a provider-specific price list and economy |
| `boolean adminUpgrade(PlayerBankData data, int pagesToAdd)` | Adds pages for free, capped at `maxPages`. Does not close an open bank window; wrap it in `changeWhileClosed` (below) for players who may have the bank open |
| `CompletableFuture<Void> changeWhileClosed(PlayerBankData data, Consumer<PlayerBankData> change)` | Runs a change on a bank. When that bank is open in a window, the window is saved and closed first and the change runs on its world thread; the future completes after the change. The admin commands use it |

`upgrade(...)` checks `upgrade.enabled` and the `permissions.upgrade` feature permission like the Pages tab does.

---

## Player data and history

| Method on `BankPlugin` | Description |
|------------------------|-------------|
| `PlayerBankData getPlayerData(UUID uuid)` | The normal bank: the loaded copy for online players, otherwise read from disk (`null` when there is no file) |
| `PlayerBankData getPlayerData(UUID uuid, String worldGroup)` | A world group bank (`null` = normal bank) |
| `BankConfig getBankConfig()` | The loaded configuration |
| `BankDatabase getDatabase()` | The history database |

| Method on `BankDatabase` | Description |
|--------------------------|-------------|
| `boolean isAvailable()` | `false` when SQLite could not be opened |
| `List<BankLogEntry> getHistory(String uuid, int offset, int limit)` | Entries of one player, newest first |
| `int getHistoryCount(String uuid)` | Number of entries of one player |
| `void logTransaction(String uuid, String name, String action, String itemId, int amount)` | Writes an entry |

`BankLogEntry` has the public fields `timestamp` (milliseconds), `action`, `itemId`, `amount` and `worldGroup`.

A `PlayerBankData` read from disk is a separate copy. Changing it while the player is online can be overwritten by the loaded copy; change banks of online players through the loaded copy and with `BankService.changeWhileClosed(...)`, so an open bank window cannot write its old contents back over the change.

---

## Player bank file

`mods/kyuubisoft_bank/players/<uuid>.json` (world groups: `worlds/<group>/players/<uuid>.json`):

```json
{
  "dataVersion": 2,
  "uuid": "7743987c-9794-46a7-90c4-a53e17f9e61e",
  "username": "Steve",
  "unlockedPages": 1,
  "pages": {
    "0": {
      "Capacity": 45,
      "Items": {
        "20": {
          "Id": "Weapon_Arrow_Clearshot",
          "Quantity": 40,
          "Durability": 0.0,
          "MaxDurability": 0.0,
          "OverrideDroppedItemAnimation": false
        }
      }
    }
  },
  "history": [],
  "sortMode": "name",
  "scrollMode": false
}
```

| Field | Meaning |
|-------|---------|
| `dataVersion` | `2`: pages are stored as Hytale item containers. Version 1 files (older slot lists) are converted when they are loaded |
| `unlockedPages` | Page count |
| `pages` | One container per page, keyed by the page index from `"0"`; `Capacity` is the slot count the page was saved with, `Items` is keyed by the slot number. A page without saved data starts empty. Pages with another `Capacity` than `slotsPerPage` are fitted when the bank opens |
| `overflow` | Only present while items wait for a free slot after `slotsPerPage` was lowered: a container in the same format as a page. Its items move into the bank as soon as there is room |
| `history` | Old in-file history. It is moved into `bank.db` and emptied when the player joins |
| `sortMode` | `"name"`, `"rarity"`, `"quantity"` or missing/`null` (no sorting) |
| `scrollMode` | `true` = Scroll view, `false` = Pages view. New banks start with `true` |

Before every save the previous file is copied to `<uuid>.json.bak`. A file that cannot be loaded is copied to `<uuid>.json.unreadable-<time>` before the player gets a new, empty bank.

---

## History database

`mods/kyuubisoft_bank/bank.db` (SQLite), table `bank_transactions`:

| Column | Type | Content |
|--------|------|---------|
| `id` | INTEGER, primary key | Running number |
| `player_uuid` | TEXT | Bank owner |
| `player_name` | TEXT | Name at the time of the entry |
| `action` | TEXT | `DEPOSIT`, `WITHDRAW` or `TRANSFER`. From 2.7.0 (not released yet) also `TRANSFER_IN`: the recipient's line of a transfer (`‹ Kyuubi 300 Crowns · "reason"`); the sender's line can carry the reason too |
| `item_id` | TEXT | Item ID, or a text for coin lines (`Coin_Gold › 1,000`, `Coins › 1,250`) and transfers (`› Steve 250`). Entries written before 2.6.3 use `→` instead of `›`; the bank shows both as `›` |
| `amount` | INTEGER | Number of items (1 for "Deposit all coins" and transfers) |
| `world_group` | TEXT | Not filled in 2.6.6 |
| `created_at` | INTEGER | Time in milliseconds |

Index `idx_transactions_player` on `(player_uuid, created_at DESC)`. Entries are never deleted, also not by a bank reset.