“You can fit so many sessions in this bad boy” - Toly slapping the hood of a gently used 2012 Swig (probably)
This guide explains how to work with sessions in Swig, which allow you to create temporary authorities with limited permissions. Sessions are perfect for dApp integrations where you need to delegate authority for a specific duration.
You can find all example code in the swig-ts/examples/classic/transfer directory.
Examples with svm in the file name use LiteSVM for testing. Those without svm in the file name use a local validator. Which you can run with the bun start-validator command.
Once a session is created, you can use it to sign transactions within its duration:
Copy
Ask AI
import { SystemProgram, LAMPORTS_PER_SOL,} from '@solana/web3.js';import { fetchSwig, getSignInstructions,} from '@swig-wallet/classic';// Find the role by session keyconst swig = await fetchSwig(connection, swigAddress);const rootRole = swig.findRoleBySessionKey(dappSessionKeypair.publicKey);if (!rootRole || !rootRole.isSessionBased()) throw new Error('Role not found for authority');// Create and sign a transfer using session authorityconst transfer = SystemProgram.transfer({ fromPubkey: swigAddress, toPubkey: dappTreasury, lamports: 0.1 * LAMPORTS_PER_SOL,});const signTransfer = await getSignInstructions( swig, rootRole.id, [transfer], false, { payer: dappSessionKeypair.publicKey },);await sendTransaction(connection, signTransfer, dappSessionKeypair);
These examples can be run in different environments:
Local Validator: Use the examples with ‘local’ in the filename
Requires running a local Solana validator with bun start-validator
Real blockchain environment
Good for final testing
LiteSVM: Use examples with svm in the filename
No validator required
Instant transaction confirmation
Perfect for rapid development
Simulates the Solana runtime
Devnet: All examples work with devnet
Change connection URL to https://api.devnet.solana.com
Real network environment
Free to use with airdropped SOL
Copy
Ask AI
// Local validatorconst connection = new Connection('http://localhost:8899', 'confirmed');// Devnetconst connection = new Connection('https://api.devnet.solana.com', 'confirmed');
LiteSVM is recommended for initial development as it provides the fastest feedback loop. Move to local validator or devnet for more thorough testing.