Manage Wallets

This guide shows you how to create wallets, store credentials, organize them with collections and tags, and create verifiable presentations.

Quick Example

Here’s a complete example that creates a wallet, stores a credential, and organizes it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import org.trustweave.trust.TrustWeave
import org.trustweave.did.resolver.DidResolutionResult
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    // Create TrustWeave instance
    val trustWeave = TrustWeave.build {
        keys {
            provider(IN_MEMORY)
            algorithm(ED25519)
        }
        did {
            method(KEY) {
                algorithm(ED25519)
            }
        }
    }

    // Create wallet
    import org.trustweave.trust.types.WalletCreationResult
    import org.trustweave.trust.types.DidCreationResult
    import org.trustweave.trust.types.IssuanceResult
    
    val walletResult = trustWeave.wallet {
        holder("did:key:holder-placeholder")
    }
    
    import org.trustweave.trust.types.getOrThrowDid
    import org.trustweave.trust.types.getOrThrow
    import org.trustweave.did.resolver.DidResolutionResult
    import org.trustweave.did.identifiers.extractKeyId
    
    // Helper extension for resolution results
    fun DidResolutionResult.getOrThrow() = when (this) {
        is DidResolutionResult.Success -> this.document
        else -> throw IllegalStateException("Failed to resolve DID: ${this.errorMessage ?: "Unknown error"}")
    }
    
    val wallet = trustWeave.wallet {
        holder("did:key:holder")
    }.getOrThrow()

    // Issue and store credential
    val issuerDid = trustWeave.createDid { method(KEY) }.getOrThrowDid()
    
    // Get key ID for signing
    val issuerDocument = trustWeave.resolveDid(issuerDid).getOrThrow()
    val issuerKeyId = issuerDocument.verificationMethod.firstOrNull()?.extractKeyId()
        ?: throw IllegalStateException("No verification method found")
    
    val credential = trustWeave.issue {
        credential {
            type("VerifiableCredential", "PersonCredential")
            issuer(issuerDid)
            subject {
                id("did:key:holder-placeholder")
                "name" to "Alice Example"
            }
        }
        signedBy(issuerDid)
    }.getOrThrow()

    val credentialId = wallet.store(credential)
    println("✅ Stored credential: $credentialId")
}

Expected Output:

1
✅ Stored credential: urn:uuid:...

Step-by-Step Guide

Step 1: Create a Wallet

Create a wallet for a holder:

1
2
3
4
5
import org.trustweave.trust.types.getOrThrow

val wallet = trustWeave.wallet {
    holder("did:key:holder")
}.getOrThrow()

Step 2: Store Credentials

Store credentials in the wallet:

1
2
val credentialId = wallet.store(credential)
println("Stored credential ID: $credentialId")

Step 3: Retrieve Credentials

Get credentials by ID or list all:

1
2
3
4
5
// Get by ID
val credential = wallet.get(credentialId)

// List all
val allCredentials = wallet.list()

Step 4: Organize Credentials (Optional)

Use collections and tags to organize credentials:

1
2
3
4
5
6
7
8
9
10
wallet.withOrganization { org ->
    // Create collection
    val collectionId = org.createCollection("Education", "Academic credentials")

    // Add credential to collection
    org.addToCollection(credentialId, collectionId)

    // Add tags
    org.tagCredential(credentialId, setOf("degree", "verified"))
}

Creating Wallets

Basic Wallet

Create a simple wallet for credential storage:

1
2
3
4
5
6
7
8
9
10
11
val walletResult = trustWeave.wallet {
    holder("did:key:holder")
}

val wallet = when (walletResult) {
    is WalletCreationResult.Success -> walletResult.wallet
    else -> {
        println("Failed to create wallet: ${walletResult.reason}")
        return@runBlocking // or handle appropriately
    }
}

Wallet with Organization

Enable organization features (collections, tags, metadata):

1
2
3
4
5
6
7
8
9
10
11
12
val walletResult = trustWeave.wallet {
    holder("did:key:holder")
    enableOrganization()
}

val wallet = when (walletResult) {
    is WalletCreationResult.Success -> walletResult.wallet
    else -> {
        println("Failed to create wallet: ${walletResult.reason}")
        return@runBlocking // or handle appropriately
    }
}

Wallet with Presentation

Enable presentation creation:

1
2
3
4
5
6
7
8
9
10
11
12
val walletResult = trustWeave.wallet {
    holder("did:key:holder")
    enablePresentation()
}

val wallet = when (walletResult) {
    is WalletCreationResult.Success -> walletResult.wallet
    else -> {
        println("Failed to create wallet: ${walletResult.reason}")
        return@runBlocking // or handle appropriately
    }
}

Enable all features:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
val walletResult = trustWeave.wallet {
    holder("did:key:holder")
    id("my-wallet-id")  // Optional: custom wallet ID
    enableOrganization()
    enablePresentation()
}

val wallet = when (walletResult) {
    is WalletCreationResult.Success -> walletResult.wallet
    else -> {
        println("Failed to create wallet: ${walletResult.reason}")
        return@runBlocking // or handle appropriately
    }
}

Storing Credentials

Basic Storage

Store a single credential:

1
val credentialId = wallet.store(credential)

Batch Storage

Store multiple credentials:

1
2
3
val credentials = listOf(credential1, credential2, credential3)
val credentialIds = credentials.map { wallet.store(it) }
println("Stored ${credentialIds.size} credentials")

Storage with Error Handling

Handle storage errors:

1
2
3
4
5
6
7
try {
    val credentialId = wallet.store(credential)
    println("Stored: $credentialId")
} catch (error: Exception) {
    println("Error: ${error.message}")
    error.printStackTrace()
}

Organizing Credentials

Collections

Group credentials into collections:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
wallet.withOrganization { org ->
    // Create collection
    val educationId = org.createCollection(
        name = "Education",
        description = "Academic credentials"
    )

    // Add credential to collection
    org.addToCollection(credentialId, educationId)

    // Get credentials in collection
    val educationCreds = org.getCredentialsInCollection(educationId)

    // List all collections
    val collections = org.listCollections()
}

Tags

Tag credentials for flexible querying:

1
2
3
4
5
6
7
8
9
10
11
12
13
wallet.withOrganization { org ->
    // Add tags
    org.tagCredential(credentialId, setOf("degree", "verified", "active"))

    // Get tags for credential
    val tags = org.getTags(credentialId)

    // Find credentials by tag
    val verifiedCreds = org.findByTag("verified")

    // Get all tags
    val allTags = org.getAllTags()
}

Metadata

Add custom metadata to credentials:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
wallet.withOrganization { org ->
    // Add metadata
    org.addMetadata(credentialId, mapOf(
        "category" to "education",
        "storedAt" to System.currentTimeMillis(),
        "source" to "university"
    ))

    // Get metadata
    val metadata = org.getMetadata(credentialId)

    // Add notes
    org.updateNotes(credentialId, "Important credential for job applications")
}

Querying Credentials

List All Credentials

Get all credentials in the wallet:

1
val allCredentials = wallet.list()

Query with Filters

Query credentials using filters:

1
2
3
4
5
val results = wallet.query {
    byIssuer("did:key:issuer")
    notExpired()
    byType("PersonCredential")
}

Query by Collection

Get credentials in a specific collection:

1
2
3
4
5
6
wallet.withOrganization { org ->
    val collection = org.listCollections().firstOrNull { it.name == "Education" }
    if (collection != null) {
        val creds = org.getCredentialsInCollection(collection.id)
    }
}

Query by Tag

Find credentials with specific tags:

1
2
3
4
wallet.withOrganization { org ->
    val verifiedCreds = org.findByTag("verified")
    val activeCreds = org.findByTag("active")
}

Creating Presentations

Basic Presentation

Create a verifiable presentation:

1
2
3
4
5
6
7
8
9
10
11
12
wallet.withPresentation { pres ->
    val presentation = pres.createPresentation(
        credentialIds = listOf(credentialId),
        holderDid = "did:key:holder",
        options = PresentationOptions(
            holderDid = "did:key:holder",
            challenge = "job-application-${System.currentTimeMillis()}"
        )
    )

    println("Created presentation: ${presentation.id}")
}

Selective Disclosure

Create a presentation with selective disclosure:

1
2
3
4
5
6
7
8
wallet.withPresentation { pres ->
    val presentation = pres.createSelectiveDisclosure(
        credentialIds = listOf(credentialId),
        disclosedFields = listOf("name", "email"),  // Only reveal these fields
        holderDid = "did:key:holder",
        options = PresentationOptions(...)
    )
}

Wallet Capabilities

Check what capabilities a wallet supports:

1
2
3
4
5
6
7
8
9
10
11
12
13
// Check if wallet supports organization
if (wallet is CredentialOrganization) {
    // Use organization features
}

// Using extension functions (recommended)
wallet.withOrganization { org ->
    // Organization features available
}

wallet.withPresentation { pres ->
    // Presentation features available
}

Common Patterns

Pattern 1: Organize After Storage

Organize credentials immediately after storing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
val credentialId = wallet.store(credential)

wallet.withOrganization { org ->
    // Create or get collection
    val collectionId = org.createCollection("Work", "Professional credentials")

    // Add to collection
    org.addToCollection(credentialId, collectionId)

    // Add tags
    org.tagCredential(credentialId, setOf("work", "verified"))

    // Add metadata
    org.addMetadata(credentialId, mapOf(
        "storedAt" to System.currentTimeMillis()
    ))
}

Pattern 2: Query and Organize

Query credentials and organize them:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Find all education credentials
val educationCreds = wallet.query {
    byType("EducationCredential")
}

// Organize them
wallet.withOrganization { org ->
    val collectionId = org.createCollection("Education", "All education credentials")
    educationCreds.forEach { cred ->
        val credId = wallet.store(cred)  // If not already stored
        org.addToCollection(credId, collectionId)
        org.tagCredential(credId, setOf("education"))
    }
}

Pattern 3: Wallet Statistics

Get wallet statistics:

1
2
3
4
val stats = wallet.getStatistics()
println("Total credentials: ${stats.totalCredentials}")
println("Collections: ${stats.collectionsCount}")
println("Tags: ${stats.tagsCount}")

Error Handling

Wallet operations return sealed results. Always handle errors:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import org.trustweave.trust.types.WalletCreationResult

val walletResult = trustWeave.wallet {
    holder("did:key:holder")
}

val wallet = when (walletResult) {
    is WalletCreationResult.Success -> walletResult.wallet
    is WalletCreationResult.Failure.InvalidHolderDid -> {
        println("Invalid holder DID: ${walletResult.holderDid}")
        println("Reason: ${walletResult.reason}")
        return@runBlocking // or handle appropriately
    }
    is WalletCreationResult.Failure.FactoryNotConfigured -> {
        println("Wallet factory not configured: ${walletResult.reason}")
        return@runBlocking
    }
    is WalletCreationResult.Failure.StorageFailed -> {
        println("Storage failed: ${walletResult.reason}")
        walletResult.cause?.printStackTrace()
        return@runBlocking
    }
    is WalletCreationResult.Failure.Other -> {
        println("Error: ${walletResult.reason}")
        walletResult.cause?.printStackTrace()
        return@runBlocking
    }
}

// Wallet operations (store, get, list) may still throw exceptions
// or return Result types depending on the implementation
val credentialId = wallet.store(credential)

API Reference

For complete API documentation, see:

Next Steps

Ready to issue credentials?

Want to create presentations?

  • Enable presentation capability and use withPresentation { }

Want to learn more?


This site uses Just the Docs, a documentation theme for Jekyll.