Skip to main content

Create Application Sessions

After connecting to a ClearNode and checking your channel balances, you can create application sessions to interact with specific applications on the state channel network. Application sessions allow you to perform off-chain transactions and define custom behavior for your interactions.

Understanding Application Sessions

Application sessions in Nitrolite allow you to:

  • Create isolated environments for specific interactions
  • Define rules for off-chain transactions
  • Specify how funds are allocated between participants
  • Implement custom application logic and state management

An application session serves as a mechanism to track and manage interactions between participants, with the ClearNode acting as a facilitator.

Creating an Application Session

To create an application session, you'll use the createAppSessionMessage helper from NitroliteRPC. Here's how to do it:

import { createAppSessionMessage } from '@erc7824/nitrolite';
import { useCallback } from 'react';

function useCreateApplicationSession() {
const createApplicationSession = useCallback(
async (
signer,
sendRequest,
participantA,
participantB,
amount,
) => {
try {
// Define the application parameters
const appDefinition = {
protocol: 'nitroliterpc',
participants: [participantA, participantB],
weights: [100, 0], // Weight distribution for consensus
quorum: 100, // Required consensus percentage
challenge: 0, // Challenge period
nonce: Date.now(), // Unique identifier
};

// Define allocations with asset type instead of token address
const allocations = [
{
participant: participantA,
asset: 'usdc',
amount: amount,
},
{
participant: participantB,
asset: 'usdc',
amount: '0',
},
];

// Create a signed message using the createAppSessionMessage helper
const signedMessage = await createAppSessionMessage(
signer.sign,
[
{
definition: appDefinition,
allocations: allocations,
},
]
);

// Send the signed message to the ClearNode
const response = await sendRequest(signedMessage);

// Handle the response
if (response && response[0] && response[0].app_session_id) {
// Store the app session ID for future reference
localStorage.setItem('app_session_id', response[0].app_session_id);
return { success: true, app_session_id: response[0].app_session_id, response };
} else {
return { success: true, response };
}
} catch (error) {
console.error('Error creating application session:', error);
return {
success: false,
error: error instanceof Error
? error.message
: 'Unknown error during session creation',
};
}
},
[]
);

return { createApplicationSession };
}

// Usage example
function MyComponent() {
const { createApplicationSession } = useCreateApplicationSession();

const handleCreateSession = async () => {
// Define your WebSocket send wrapper
const sendRequest = async (payload) => {
return new Promise((resolve, reject) => {
// Assuming ws is your WebSocket connection
const handleMessage = (event) => {
try {
const message = JSON.parse(event.data);
if (message.res && message.res[1] === 'create_app_session') {
ws.removeEventListener('message', handleMessage);
resolve(message.res[2]);
}
} catch (error) {
console.error('Error parsing message:', error);
}
};

ws.addEventListener('message', handleMessage);
ws.send(payload);

// Set timeout to prevent hanging
setTimeout(() => {
ws.removeEventListener('message', handleMessage);
reject(new Error('App session creation timeout'));
}, 10000);
});
};

const result = await createApplicationSession(
walletSigner, // Your signer object
sendRequest, // Function to send the request
'0xYourAddress', // Your address
'0xOtherAddress', // Other participant's address
'100', // Amount
);

if (result.success) {
console.log(`Application session created with ID: ${result.app_session_id}`);
} else {
console.error(`Failed to create application session: ${result.error}`);
}
};

return (
<button onClick={handleCreateSession}>Create Application Session</button>
);
}

Key Components of an Application Session

When creating an application session, you need to define several key components:

ComponentDescriptionExample
ProtocolIdentifier for the application protocol"nitroliterpc"
ParticipantsArray of participant addresses[userAddress, counterpartyAddress]
WeightsWeight distribution for consensus[100, 0] for user-controlled, [50, 50] for equal
QuorumRequired percentage for consensusUsually 100 for full consensus
ChallengeTime period for disputing state0 for no challenge period
NonceUnique identifierTypically Date.now()
AllocationsArray of allocation objects with:[{ participant: "0xAddress", asset: "usdc", amount: "100" }]
- participant: Address of the participant
- asset: Asset identifier (e.g., "usdc", "eth")
- amount: String amount with precision

Response Components

When a ClearNode responds to your application session creation request, it provides:

ComponentDescriptionExample
app_session_idUnique identifier for the application session"0x0ac588b2924edbbbe34bb4c51d089771bd7bd7018136c8c4317624112a8c9f79"
statusCurrent state of the application session"open"

Understanding the Response

When you create an application session, the ClearNode responds with information about the created session:

// Example response
{
"res": [
2, // Request ID
"create_app_session", // Method name
[
{
"app_session_id": "0x0ac588b2924edbbbe34bb4c51d089771bd7bd7018136c8c4317624112a8c9f79", // Session ID
"status": "open"
}
],
1631234567890 // Timestamp
],
"sig": ["0xSignature"]
}

The most important part of the response is the app_session_id, which you'll need for all future interactions with this application session.

Application Session Use Cases

Application sessions can be used for various scenarios:

  1. Peer-to-peer payments: Direct token transfers between users
  2. Gaming: Turn-based games with state transitions
  3. Content access: Pay-per-use access to digital content
  4. Service payments: Metered payment for API or service usage
  5. Multi-party applications: Applications involving more than two participants

Best Practices

When working with application sessions, follow these best practices:

  1. Store the app_session_id securely: You'll need it for all session-related operations
  2. Verify session creation: Check for successful creation before proceeding
  3. Handle timeouts: Implement proper timeout handling for session creation
  4. Clean up listeners: Always remove message event listeners to prevent memory leaks
  5. Handle errors gracefully: Provide clear error messages to users

Next Steps

After creating an application session, you can:

  1. Use the session for application-specific transactions
  2. Check your channel balances to monitor funds
  3. Close the application session when you're done

For advanced use cases, see our detailed documentation on application workflows.