Building a Stateless VIDA
Stateless VIDAs are lightweight, fast, and simple applications that do not require validating or maintaining historical data or consistent state across its execution instances. They are ideal for non-critical use cases such as chat rooms, simple games, or other applications where speed and ease of development are prioritized over strict consistency.
Steps to Build a Stateless VIDA
1. Select an ID for Your VIDA
Every VIDA requires a unique identifier, which is an 8-byte variable. This ID ensures the PWR Chain knows which transactions belong to your application.
Why 8 bytes? It minimizes storage requirements while allowing for 18 quintillion unique IDs.
//generate a random long value
long vidaId = new SecureRandom().nextLong();
System.out.println(vidaId);
//Save the vidaId
2. Import the PWR SDK
The PWR SDK is your toolkit for interacting with the PWR Chain. It allows you to create wallets, send transactions, and read data from the blockchain.
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.github.pwrlabs</groupId>
<artifactId>pwrj</artifactId>
<version>11.4.1</version>
</dependency>
</dependencies>
Make sure to use the latest version. Check https://github.com/pwrlabs/pwrj for the latest release
import com.github.pwrlabs.pwrj.protocol.PWRJ;
3. Initializing PWR with an RPC Endpoint
To interact with the PWR Chain, initialize a PWR object (e.g., PWRJ
for Java, PWRPY
for Python). This object serves as your gateway to the blockchain.
What is an RPC Node?
An RPC (Remote Procedure Call) node processes blockchain requests, such as transactions and data queries. You can use a public node (e.g., https://pwrrpc.pwrlabs.io
) or run your own for better control and security.
PWRJ pwrj = new PWRJ("https://pwrrpc.pwrlabs.io");
This setup enables seamless interaction with the PWR Chain for your VIDA.
4. Create and Fund a Wallet
A wallet is essential for signing transactions and paying minimal fees on the PWR Chain.
Steps:
Create a new wallet or load an existing one.
Save the wallet securely in an encrypted file.
Fund it using the PWR Chain faucet (for test coins). You can check your PWR coins balance on the PWR Chain Explorer by putting your address in the search bar.
private static PWRFalconWallet createWallet(PWRJ pwrj, String password) {
try {
//Try to load an existing wallet
PWRFalconWallet wallet = PWRFalconWallet.loadWallet(pwrj, "wallet", password);
// If the wallet is null, it means it was not found or could not be loaded
// Create new wallet
if(wallet == null) {
wallet = new PWRFalconWallet(12, pwrj);
wallet.storeWallet("wallet", password);
}
return wallet;
} catch (Exception e) {
System.err.println("Failed to create or load wallet: " + e.getMessage());
e.printStackTrace();
return null;
}
}
5. Define Transaction Data Structure
While PWR Chain stores all transaction data as raw byte arrays, VIDAs can encode this data into structured formats like JSON. Defining a schema for your transactions ensures consistency, simplifies development, and enables collaboration across teams.
Why Define a Schema?
Consistency: Ensures all transactions follow a predictable format.
Documentation: Serves as a reference for developers interacting with your VIDA.
Validation: Helps catch malformed data early.
Example:
[
{
"action": "send-message-v1",
"message": "Hello World!"
},
{
"action": "add-reaction-v1",
"message-hash": "0x54ef...",
"reaction": "thumbs-up"
}
]
6. Send Data to PWR Chain
After defining your transaction's data structure, you can start sending transactions to PWR Chain. Submit transactions to the PWR Chain to record user actions or data.
//Write transaction data
JSONObject jsonObject = new JSONObject();
jsonObject.put("action", "send-message-v1");
jsonObject.put("message", "Hello World!");
byte[] data = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
//Send transaction
Response response = wallet.sendVmDataTransaction(vidaId, data, loadedWallet.getNonce());
if(response.isSuccess()) {
System.out.println("Transaction sent successfully!");
System.out.println("Transaction hash: " + response.getTransactionHash());
}
else System.out.println("Transaction failed: " + response.getError());
7. Read Data from PWR Chain & Handle it.
The PWR SDK provides functions to easily read and handle data from PWR Chain.
PWRJ pwrj = new PWRJ("https://pwrrpc.pwrlabs.io/");
long vidaId = 1; // Replace with your VIDA's ID
/*Since our VIDA is global chat room and we don't care about historical messages,
we will start reading transactions startng from the latest PWR Chain block*/
long startingBlock = pwrj.getBlockNumber();
VidaTransactionSubscription vidaTransactionSubscription = pwrj.subscribeToVidaTransactions(pwrj, vidaId, startingBlock, (transaction) -> {
VmDataTransaction vmDataTransaction = transaction;
//Get the address of the transaction sender
String sender = vmDataTransaction.getSender();
//Get the data sent in the transaction (In Hex Format)
String data = vmDataTransaction.getData();
try {
//Decode the data from Hex to byte array
if (data.startsWith("0x")) data = data.substring(2);
byte[] dataBytes = Hex.decode(data);
//Convert the byte array to a JSON Object
JSONObject jsonObject = new JSONObject(new String(dataBytes));
String action = jsonObject.optString("action", "no-action");
//Check the action and execute the necessary code
if (action.equalsIgnoreCase("send-message-v1")) {
String message = jsonObject.getString("message");
System.out.println("Message from " + sender + ": " + message);
} else {
//ignore
}
} catch (Exception e) {
e.printStackTrace();
//This most likely indicates Malformed data from the sender
}
});
//To pause, resume, and stop the subscription
vidaTransactionSubscription.pause();
vidaTransactionSubscription.resume();
vidaTransactionSubscription.stop();
vidaTransactionSubscription.start();
//To get the block number of the latest checked PWR Chain block
vidaTransactionSubscription.getLatestCheckedBlock();
8. Make Your App Public
Once your VIDA is ready, share it with others by publishing it:
Option 1: Open-source your code on GitHub with clear instructions.
Option 2: Publish it on the PWR Chain registry for decentralized discovery. (Coming Soon)
Key Considerations for Stateless VIDAs
No State Management: Stateless VIDAs do not track or validate past transactions, making them fast but unsuitable for critical use cases.
Ideal Use Cases: Applications prioritizing speed and simplicity over consistency (e.g., chat apps, simple games).
By following these steps, you can build a lightweight and efficient Stateless VIDA that leverages the power of PWR Chain while keeping development simple!
Last updated
Was this helpful?