### Get Economy Service Implementation
Source: https://gitlab.com/mintychochip/mint/-/blob/main/README.md
Retrieves an instance of the EconomyService from the Mint API. This example demonstrates how to check if an implementation is loaded before attempting to use it.
```java
EconomyService service = Mint.ECONOMY.get();
if (service ==null) {
// No economy implementation is loaded
return;
}
```
--------------------------------
### Check and Get Economy Service for Consumers
Source: https://gitlab.com/mintychochip/mint/-/blob/main/README.md
Demonstrates how plugins depending on the economy service should check for availability before retrieval. It's crucial not to shade or relocate the API to maintain the service holder pattern.
```java
if (!Mint.ECONOMY.isLoaded()) {
// No implementation is available
return;
}
EconomyService service = Mint.ECONOMY.get();
```
--------------------------------
### Deposit Funds using Java
Source: https://context7.com/mintychochip/mint/llms.txt
Deposit funds into a specified account using the EconomyService. This example demonstrates creating a transaction context with a player actor and handling the commit and potential exceptions during the deposit operation.
```java
import dev.mintychochip.mint.EconomyService;
import dev.mintychochip.mint.Transaction;
import dev.mintychochip.mint.TransactionContext;
import dev.mintychochip.mint.TransactionResult;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
import java.util.UUID;
public void depositFunds(EconomyService economy, Player player, UUID accountId) {
// Create transaction context with player actor
TransactionContext ctx = TransactionContext.create(
new TransactionContext.PlayerActor(player),
"Daily login bonus"
);
// Begin transaction and deposit funds
Transaction txn = economy.beginTransaction(accountId, ctx);
BigDecimal amount = new BigDecimal("50.00");
txn.deposit(amount)
.commit()
.thenAccept(result -> {
player.sendMessage("Deposited $" + amount + " to your account");
player.sendMessage("Transaction ID: " + result.getId());
player.sendMessage("Total operations: " + result.getOperationCount());
})
.exceptionally(ex -> {
player.sendMessage("Deposit failed: " + ex.getMessage());
return null;
});
}
```
--------------------------------
### Chain Multiple Operations in Atomic Transaction with Java
Source: https://context7.com/mintychochip/mint/llms.txt
Demonstrates chaining multiple financial operations (deposits and withdrawals) into a single atomic transaction. All operations are executed together, ensuring data consistency. The example uses custom actors and logs transaction details upon completion or failure. Dependencies include dev.mintychochip.mint.* classes.
```java
import dev.mintychochip.mint.EconomyService;
import dev.mintychochip.mint.Transaction;
import dev.mintychochip.mint.TransactionContext;
import dev.mintychochip.mint.TransactionResult;
import java.math.BigDecimal;
import java.util.UUID;
public void complexTransaction(EconomyService economy, UUID accountId) {
// Create custom actor
TransactionContext ctx = TransactionContext.create(
TransactionContext.Actor.simple("DailyRewardSystem"),
"Daily quest completion with penalty"
);
Transaction txn = economy.beginTransaction(accountId, ctx);
// Chain multiple operations - all execute atomically or none execute
txn.deposit(new BigDecimal("100.00")) // Quest reward
.withdraw(new BigDecimal("25.00")) // Quest completion fee
.deposit(new BigDecimal("50.00")) // Bonus reward
.commit()
.thenAccept(result -> {
System.out.println("Transaction state: " + result.getState());
System.out.println("Total operations: " + result.getOperationCount());
System.out.println("Net amount: $" + result.getTotalAmount());
// Iterate all operations
for (TransactionOperation op : result.getOperations()) {
System.out.println("Op type: " + op.type() +
", Amount: $" + op.amount() +
", Before: $" + op.balanceBefore() +
", After: $" + op.balanceAfter());
}
})
.exceptionally(ex -> {
System.err.println("Complex transaction failed and rolled back");
return null;
});
}
```
--------------------------------
### Perform Atomic Transaction with Mint API
Source: https://gitlab.com/mintychochip/mint/-/blob/main/README.md
Executes a series of financial operations atomically using the Mint API's Transaction system. This example shows creating a transaction context, initiating a deposit, and handling the asynchronous result or potential exceptions.
```java
TransactionContext ctx = TransactionContext.create(
TransactionContext.Actor.player(player),
"Payment for service"
);
Transaction txn = service.beginTransaction(accountId, ctx);
txn.deposit(new BigDecimal("100.00")).commit()
.thenAccept(result -> {
// Successful Transaction
})
.exceptionally(ex -> {
// Handle failure (e.g., insufficient funds on withdraw)
return null;
});
```
--------------------------------
### Manually Rollback Transaction Before Commit with Java
Source: https://context7.com/mintychochip/mint/llms.txt
Illustrates how to manually rollback a transaction before it is committed, ensuring that no changes are applied. This is useful for conditional operations where further checks might determine if the transaction should proceed. The example shows staging operations and then conditionally committing or rolling back. Dependencies include dev.mintychochip.mint.* classes.
```java
import dev.mintychochip.mint.EconomyService;
import dev.mintychochip.mint.Transaction;
import dev.mintychochip.mint.TransactionContext;
import java.math.BigDecimal;
import java.util.UUID;
public void conditionalTransaction(EconomyService economy, UUID accountId,
boolean shouldProceed) {
TransactionContext ctx = TransactionContext.create(
TransactionContext.Actor.simple("ConditionalSystem"),
"Conditional balance update"
);
Transaction txn = economy.beginTransaction(accountId, ctx);
// Stage operations
txn.deposit(new BigDecimal("1000.00"));
// Check transaction state
if (txn.getState() == Transaction.State.ACTIVE) {
if (shouldProceed) {
// Commit the transaction
txn.commit().thenAccept(result -> {
System.out.println("Transaction committed");
});
} else {
// Rollback without executing
txn.rollback();
System.out.println("Transaction rolled back - no changes applied");
System.out.println("Final state: " + txn.getState()); // ROLLED_BACK
}
}
}
```
--------------------------------
### Create and Manage Player Accounts Asynchronously (Java)
Source: https://context7.com/mintychochip/mint/llms.txt
This Java snippet illustrates how to asynchronously manage player accounts using the Mint Economy API. It includes checking for an existing account, creating a new one if it doesn't exist, or retrieving an existing account. The operations are non-blocking and use `CompletableFuture` for handling results and potential errors.
```java
import dev.mintychochip.mint.EconomyService;
import dev.mintychochip.mint.Account;
import org.bukkit.entity.Player;
import java.util.UUID;
import java.util.Optional;
public void setupPlayerAccount(EconomyService economy, Player player) {
UUID playerId = player.getUniqueId();
// Check if player has an account
economy.hasAccount(playerId).thenAccept(exists -> {
if (!exists) {
// Create new account with player name
economy.createAccount(playerId, player.getName())
.thenAccept(account -> {
player.sendMessage("Account created! Balance: " + account.amount());
})
.exceptionally(ex -> {
player.sendMessage("Failed to create account: " + ex.getMessage());
return null;
});
} else {
// Retrieve existing account
economy.getAccount(playerId)
.thenAccept(optAccount -> {
optAccount.ifPresentOrElse(
account -> {
player.sendMessage("Welcome back! Balance: " + account.amount());
player.sendMessage("Account created: " + account.createdAt());
},
() -> player.sendMessage("Account lookup failed")
);
});
}
});
}
```
--------------------------------
### Register Economy Service Provider (Java)
Source: https://context7.com/mintychochip/mint/llms.txt
This code demonstrates how to register a custom economy service implementation with the Mint API. It involves creating an instance of your `EconomyService` implementation and registering it with a specific priority. The registration and unregistration should typically happen during plugin enable and disable events.
```java
import dev.mintychochip.mint.Mint;
import dev.mintychochip.mint.EconomyService;
import dev.mintychochip.mint.ServiceHolder;
import dev.mintychochip.mint.Account;
import dev.mintychochip.mint.Transaction;
import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class MyEconomyPlugin extends JavaPlugin {
private EconomyService implementation;
@Override
public void onEnable() {
// Create your economy implementation
implementation = new MyEconomyService();
// Register with HIGH priority (will override NORMAL priority services)
Mint.ECONOMY.register(implementation, ServiceHolder.Priority.HIGH);
getLogger().info("Economy service registered successfully");
}
@Override
public void onDisable() {
// Unregister when plugin disables
if (implementation != null) {
Mint.ECONOMY.unregister(implementation);
}
}
}
```
--------------------------------
### Add Mint API Dependency for Gradle
Source: https://gitlab.com/mintychochip/mint/-/blob/main/README.md
Configures Gradle to use the Mint API by specifying the Maven repository and the API dependency. Ensure you are using a compatible Kotlin version for Gradle.
```kotlin
repositories {
maven("https://gitlab.com/api/v4/projects/77453344/packages/maven")
}
dependencies {
compileOnly("dev.mintychochip:mint-api:1.0")
}
```
--------------------------------
### Add Mint API Dependency for Maven
Source: https://gitlab.com/mintychochip/mint/-/blob/main/README.md
Configures Maven to use the Mint API by defining the Maven repository and the API dependency in the pom.xml file. The 'provided' scope is used as the API is expected to be available at runtime.
```xml
gitlab
https://gitlab.com/api/v4/projects/77453344/packages/maven
dev.mintychochip
mint-api
1.0
provided
```
--------------------------------
### Register Economy Service Implementation
Source: https://gitlab.com/mintychochip/mint/-/blob/main/README.md
Registers a custom EconomyService implementation with the Mint API. Implementations can be registered with different priorities, and the highest priority service is selected.
```java
EconomyService impl = new MyEconomyService();
Mint.ECONOMY.register(impl, ServiceHolder.Priority.NORMAL);
```
--------------------------------
### Withdraw Funds using Java
Source: https://context7.com/mintychochip/mint/llms.txt
Withdraw funds from an account using the EconomyService. This snippet shows how to initiate a transaction with a plugin actor, commit the withdrawal, and specifically handle insufficient funds exceptions, along with other general failures.
```java
import dev.mintychochip.mint.EconomyService;
import dev.mintychochip.mint.Transaction;
import dev.mintychochip.mint.TransactionContext;
import dev.mintychochip.mint.TransactionException;
import org.bukkit.plugin.Plugin;
import java.math.BigDecimal;
import java.util.UUID;
public void purchaseItem(EconomyService economy, Plugin plugin, UUID accountId, BigDecimal price) {
// Create plugin actor for automated purchases
TransactionContext ctx = TransactionContext.create(
new TransactionContext.PluginActor(plugin),
"Item purchase from shop"
);
Transaction txn = economy.beginTransaction(accountId, ctx);
txn.withdraw(price)
.commit()
.thenAccept(result -> {
plugin.getLogger().info("Purchase successful: $" + price);
plugin.getLogger().info("Committed at: " + result.getCommitTime());
})
.exceptionally(ex -> {
if (ex.getCause() instanceof TransactionException) {
plugin.getLogger().warning("Insufficient funds for purchase");
} else {
plugin.getLogger().severe("Purchase failed: " + ex.getMessage());
}
return null;
});
}
```
--------------------------------
### Check Account Balances using Java
Source: https://context7.com/mintychochip/mint/llms.txt
Retrieve balances for single or multiple accounts using the EconomyService. This method handles asynchronous operations and provides error handling for balance fetching. It's efficient for batch fetching multiple balances.
```java
import dev.mintychochip.mint.EconomyService;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
public void checkBalances(EconomyService economy, UUID accountId) {
// Get single account balance
economy.getBalance(accountId)
.thenAccept(balance -> {
System.out.println("Account balance: $" + balance);
})
.exceptionally(ex -> {
System.err.println("Failed to fetch balance: " + ex.getMessage());
return null;
});
}
public void checkMultipleBalances(EconomyService economy, List accountIds) {
// Batch fetch multiple balances (more efficient than individual calls)
economy.getBalances(accountIds)
.thenAccept(balances -> {
for (int i = 0; i < accountIds.size(); i++) {
System.out.println("Account " + accountIds.get(i) +
": $" + balances.get(i));
}
})
.exceptionally(ex -> {
System.err.println("Batch balance fetch failed: " + ex.getMessage());
return null;
});
}
```
--------------------------------
### Transfer Funds Between Accounts with Java
Source: https://context7.com/mintychochip/mint/llms.txt
Atomically transfers funds from a sender's account to a receiver's account using the EconomyService. It handles transaction initiation, transfer execution, and provides feedback on success or failure. Dependencies include the dev.mintychochip.mint.* classes.
```java
import dev.mintychochip.mint.EconomyService;
import dev.mintychochip.mint.Transaction;
import dev.mintychochip.mint.TransactionContext;
import dev.mintychochip.mint.TransactionOperation;
import org.bukkit.entity.Player;
import java.math.BigDecimal;
import java.util.UUID;
import java.util.List;
public void transferMoney(EconomyService economy, Player sender,
UUID senderAccount, UUID receiverAccount, BigDecimal amount) {
TransactionContext ctx = TransactionContext.create(
new TransactionContext.PlayerActor(sender),
"Player-to-player transfer"
);
// Transfer FROM sender account TO receiver account
Transaction txn = economy.beginTransaction(senderAccount, ctx);
txn.transferTo(receiverAccount, amount)
.commit()
.thenAccept(result -> {
sender.sendMessage("Transfer successful: $" + amount);
// Get operations for sender account
List senderOps = result.getOperationsFor(senderAccount);
for (TransactionOperation op : senderOps) {
sender.sendMessage("Your balance: $" + op.balanceBefore() +
" -> $" + op.balanceAfter());
}
// Transaction timing
long durationMs = java.time.Duration.between(
result.getStartTime(),
result.getCommitTime()
).toMillis();
sender.sendMessage("Transfer completed in " + durationMs + "ms");
})
.exceptionally(ex -> {
sender.sendMessage("Transfer failed: " + ex.getMessage());
return null;
});
}
```
--------------------------------
### Delete Player Account Asynchronously in Java
Source: https://context7.com/mintychochip/mint/llms.txt
Asynchronously deletes a player's account using the EconomyService. It provides feedback to the administrator about the success or failure of the deletion operation. This method requires the EconomyService and a Player object for feedback.
```java
import dev.mintychochip.mint.EconomyService;
import org.bukkit.entity.Player;
import java.util.UUID;
public void deletePlayerAccount(EconomyService economy, Player admin, UUID targetPlayerId) {
economy.deleteAccount(targetPlayerId)
.thenAccept(deleted -> {
if (deleted) {
admin.sendMessage("Account deleted successfully");
} else {
admin.sendMessage("Account not found");
}
})
.exceptionally(ex -> {
admin.sendMessage("Failed to delete account: " + ex.getMessage());
return null;
});
}
```
--------------------------------
### Set Absolute Account Balance in Java
Source: https://context7.com/mintychochip/mint/llms.txt
Sets an account's balance to a specific target value. This is useful for resetting balances or manual administrative adjustments. It uses the EconomyService and handles asynchronous operations with commit and exception callbacks.
```java
import dev.mintychochip.mint.EconomyService;
import dev.mintychochip.mint.Transaction;
import dev.mintychochip.mint.TransactionContext;
import java.math.BigDecimal;
import java.util.UUID;
public void resetAccountBalance(EconomyService economy, UUID accountId,
BigDecimal targetBalance) {
TransactionContext ctx = TransactionContext.create(
TransactionContext.Actor.simple("AdminTool"),
"Manual balance adjustment by administrator"
);
Transaction txn = economy.beginTransaction(accountId, ctx);
// Set exact balance (useful for resets or admin commands)
txn.set(targetBalance)
.commit()
.thenAccept(result -> {
System.out.println("Balance set to: $" + targetBalance);
// Check the actual change
for (var op : result.getOperations()) {
System.out.println("Previous balance: $" + op.balanceBefore());
System.out.println("New balance: $" + op.balanceAfter());
}
})
.exceptionally(ex -> {
System.err.println("Failed to set balance: " + ex.getMessage());
return null;
});
}
```
--------------------------------
### Transfer Between Accounts
Source: https://context7.com/mintychochip/mint/llms.txt
Atomically transfer funds from one account to another. This operation ensures that the funds are deducted from the sender and added to the receiver in a single, indivisible step.
```APIDOC
## POST /api/transactions/transfer
### Description
Atomically transfer funds from one account to another. Ensures that the funds are deducted from the sender and added to the receiver in a single, indivisible step.
### Method
POST
### Endpoint
/api/transactions/transfer
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **senderAccount** (UUID) - Required - The unique identifier for the sender's account.
- **receiverAccount** (UUID) - Required - The unique identifier for the receiver's account.
- **amount** (BigDecimal) - Required - The amount of funds to transfer.
### Request Example
```json
{
"senderAccount": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"receiverAccount": "f0e1d2c3-b4a5-6789-0123-456789abcdef",
"amount": "100.50"
}
```
### Response
#### Success Response (200)
- **message** (string) - A success message indicating the transfer was completed.
- **details** (object) - Contains details about the transaction, including balances before and after.
#### Response Example
```json
{
"message": "Transfer successful.",
"details": {
"senderBalance": {
"before": "500.00",
"after": "399.50"
},
"receiverBalance": {
"before": "200.00",
"after": "300.50"
},
"transactionDurationMs": 50
}
}
```
#### Error Response (400)
- **error** (string) - A message describing the error (e.g., insufficient funds, invalid account).
#### Error Response Example
```json
{
"error": "Insufficient funds in sender account."
}
```
```
--------------------------------
### Multi-Operation Transaction
Source: https://context7.com/mintychochip/mint/llms.txt
Chain multiple operations (deposits, withdrawals) in a single atomic transaction. All operations within the chain are executed atomically, meaning they either all succeed or all fail and are rolled back.
```APIDOC
## POST /api/transactions/complex
### Description
Chain multiple operations (e.g., deposits, withdrawals) within a single atomic transaction. All operations are executed atomically; they either all succeed or all fail and are rolled back.
### Method
POST
### Endpoint
/api/transactions/complex
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **accountId** (UUID) - Required - The unique identifier for the account on which to perform operations.
- **operations** (array) - Required - A list of operations to perform. Each operation should have a 'type' (e.g., 'deposit', 'withdraw') and an 'amount'.
### Request Example
```json
{
"accountId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"operations": [
{ "type": "deposit", "amount": "100.00" },
{ "type": "withdraw", "amount": "25.00" },
{ "type": "deposit", "amount": "50.00" }
]
}
```
### Response
#### Success Response (200)
- **message** (string) - A success message indicating the transaction was completed.
- **transactionDetails** (object) - Contains details about the completed transaction, including state, operation count, net amount, and individual operation results.
#### Response Example
```json
{
"message": "Complex transaction completed successfully.",
"transactionDetails": {
"state": "COMMITTED",
"operationCount": 3,
"netAmount": "125.00",
"operations": [
{ "type": "DEPOSIT", "amount": "100.00", "balanceBefore": "0.00", "balanceAfter": "100.00" },
{ "type": "WITHDRAW", "amount": "25.00", "balanceBefore": "100.00", "balanceAfter": "75.00" },
{ "type": "DEPOSIT", "amount": "50.00", "balanceBefore": "75.00", "balanceAfter": "125.00" }
]
}
}
```
#### Error Response (400)
- **error** (string) - A message describing the error (e.g., one of the operations failed, invalid operation details).
#### Error Response Example
```json
{
"error": "Transaction failed due to insufficient funds on withdraw operation."
}
```
```
--------------------------------
### Transaction Rollback
Source: https://context7.com/mintychochip/mint/llms.txt
Manually rollback a transaction before it is committed. This allows for conditional execution of transactions, where operations can be staged and then either committed or rolled back based on certain conditions.
```APIDOC
## POST /api/transactions/rollback
### Description
Manually rollback a transaction before it is committed. This allows for conditional execution, where operations can be staged and then either committed or rolled back based on specific conditions.
### Method
POST
### Endpoint
/api/transactions/rollback
### Parameters
#### Path Parameters
None
#### Query Parameters
- **accountId** (UUID) - Required - The unique identifier for the account associated with the transaction.
- **shouldCommit** (boolean) - Required - A flag indicating whether to commit (`true`) or rollback (`false`) the staged transaction.
#### Request Body
- **operations** (array) - Optional - A list of operations to stage for the transaction. If omitted, this might be used to finalize a previously staged transaction.
### Request Example
```json
{
"accountId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"operations": [
{ "type": "deposit", "amount": "1000.00" }
]
}
```
*(Note: The `shouldCommit` parameter would typically be part of the request payload or a separate endpoint call after staging operations.)*
### Response
#### Success Response (200)
- **message** (string) - A message indicating the transaction's outcome (committed or rolled back).
- **finalState** (string) - The final state of the transaction (e.g., "COMMITTED", "ROLLED_BACK").
#### Response Example
```json
{
"message": "Transaction rolled back successfully.",
"finalState": "ROLLED_BACK"
}
```
#### Error Response (400)
- **error** (string) - A message describing the error (e.g., transaction already committed, invalid state).
#### Error Response Example
```json
{
"error": "Cannot rollback transaction that has already been committed."
}
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.