Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Build and Development Commands

### Build
```bash
mvn package
```

### Testing
```bash
# Run unit tests only
make unit
# or: mvn test -Dcucumber.filter.tags="@unit"

# Run integration tests only
make integration
# or: mvn test -Dtest=com.algorand.algosdk.integration.RunCucumberIntegrationTest -Dcucumber.filter.tags="@integration"

# Run all tests (unit + integration)
make ci-test

# Run tests with Docker test harness
make docker-test

# Start/stop test harness manually
make harness
make harness-down
```

### Examples
The `examples/` directory contains example code:
```bash
cd examples/
mvn package
java -cp target/sdk-extras-1.0-SNAPSHOT.jar com.algorand.examples.Example
```

## Architecture Overview

This is the official Java SDK for Algorand blockchain, providing client libraries for interacting with algod and indexer nodes.

### Core Package Structure

- **`account/`** - Account management, keypair generation, and logic signature accounts
- **`crypto/`** - Core cryptographic primitives (Ed25519, addresses, signatures, multisig)
- **`transaction/`** - Transaction types, builders, and atomic transaction composer
- **`v2/client/`** - REST clients for algod and indexer APIs (auto-generated from OpenAPI specs)
- **`builder/transaction/`** - Fluent transaction builders for all transaction types
- **`abi/`** - Application Binary Interface support for smart contracts
- **`mnemonic/`** - BIP39 mnemonic phrase utilities
- **`util/`** - Encoding/decoding utilities (MessagePack, Base64, etc.)

### Key Components

#### Transaction System
- **Transaction Builder Pattern**: All transaction types use fluent builders (e.g., `PaymentTransactionBuilder`, `ApplicationCallTransactionBuilder`)
- **Atomic Transaction Composer**: High-level interface for building transaction groups with ABI method calls
- **Transaction Types**: Payment, asset transfer, application calls, key registration, state proof, heartbeat

#### Client Architecture
- **AlgodClient**: REST client for algod daemon (node operations, transaction submission)
- **IndexerClient**: REST client for indexer service (historical queries, account lookups)
- **Generated Code**: Most v2 client classes are auto-generated from OpenAPI specifications

#### Cryptography
- **Ed25519**: Primary signature algorithm using BouncyCastle
- **Multisig**: M-of-N threshold signatures
- **Logic Signatures**: Delegated signing using TEAL programs
- **Address**: 32-byte public key hash with checksum

## Code Generation

The v2 client code (`v2.client.algod.*`, `v2.client.indexer.*`, `v2.client.model.*`) is generated from OpenAPI specs:
- algod.oas2.json - algod daemon API
- indexer.oas2.json - indexer service API

To regenerate clients, use the `generate_java.sh` script from the [generator](https://github.com/algorand/generator/) repository.

## Testing Framework

Uses Cucumber BDD testing with separate unit and integration test suites:
- **Unit tests**: Fast tests using mocked clients (`@unit` tags)
- **Integration tests**: Full integration with test harness (`@integration` tags)
- **Test harness**: Dockerized Algorand network for integration testing

Test files are organized under:
- `src/test/java/com/algorand/algosdk/unit/` - Unit test step definitions
- `src/test/java/com/algorand/algosdk/integration/` - Integration test step definitions
- `src/test/resources/` - Test data and response fixtures
- `test-harness/features/` - Cucumber feature files

## Development Notes

- **Java 8+ Compatibility**: Maintains Java 8 compatibility with Android support (minSdkVersion 26+)
- **Dependencies**: Uses Jackson for JSON, MessagePack for serialization, BouncyCastle for crypto
- **Maven Profiles**: Includes IDE profile for IntelliJ compatibility with mixed Java versions
- **Generated Content**: Do not manually edit generated client code - regenerate from specs instead
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# java-algorand-sdk

[![CircleCI](https://dl.circleci.com/status-badge/img/gh/algorand/java-algorand-sdk/tree/develop.svg?style=svg)](https://dl.circleci.com/status-badge/redirect/gh/algorand/java-algorand-sdk/tree/develop)
<!-- Commented out until https://github.com/softwaremill/maven-badges/issues/1009 resolved -->
<!-- [![Sonatype Central](https://maven-badges.sml.io/sonatype-central/com.algorand/algosdk/badge.svg?style=plastic)](https://maven-badges.sml.io/sonatype-central/com.algorand/algosdk/) -->

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package com.algorand.algosdk.builder.transaction;

import com.algorand.algosdk.crypto.Address;
import com.algorand.algosdk.transaction.AccessConverter;
import com.algorand.algosdk.transaction.AppBoxReference;
import com.algorand.algosdk.transaction.AppResourceRef;
import com.algorand.algosdk.transaction.ResourceRef;
import com.algorand.algosdk.transaction.Transaction;
import com.algorand.algosdk.util.Encoder;

Expand All @@ -17,6 +20,8 @@ public abstract class ApplicationBaseTransactionBuilder<T extends ApplicationBas
private List<Long> foreignApps;
private List<Long> foreignAssets;
private List<AppBoxReference> appBoxReferences;
private List<ResourceRef> access;
private List<AppResourceRef> appResourceRefs;
private Long applicationId;

/**
Expand All @@ -32,13 +37,46 @@ protected void applyTo(Transaction txn) {
Objects.requireNonNull(onCompletion, "OnCompletion is required, please file a bug report.");
Objects.requireNonNull(applicationId);

// Handle access field conversion and validation
boolean hasLegacyFields = (accounts != null && !accounts.isEmpty()) ||
(foreignApps != null && !foreignApps.isEmpty()) ||
(foreignAssets != null && !foreignAssets.isEmpty()) ||
(appBoxReferences != null && !appBoxReferences.isEmpty());

boolean hasAccessFields = (access != null && !access.isEmpty()) ||
(appResourceRefs != null && !appResourceRefs.isEmpty());

if (hasLegacyFields && hasAccessFields) {
throw new IllegalArgumentException(
"Cannot use access fields together with legacy accounts, foreignApps, foreignAssets, or boxReferences");
}

// Convert AppResourceRef to ResourceRef if provided
if (appResourceRefs != null && !appResourceRefs.isEmpty()) {
if (access != null && !access.isEmpty()) {
throw new IllegalArgumentException(
"Cannot use both AppResourceRef and ResourceRef access methods simultaneously");
}
access = AccessConverter.convertToResourceRefs(appResourceRefs, sender, applicationId);
}

// Validate ResourceRef entries
if (access != null && !access.isEmpty()) {
for (ResourceRef ref : access) {
if (ref != null) {
ref.validate();
}
}
}

if (applicationId != null) txn.applicationId = applicationId;
if (onCompletion != null) txn.onCompletion = onCompletion;
if (applicationArgs != null) txn.applicationArgs = applicationArgs;
if (accounts != null) txn.accounts = accounts;
if (foreignApps != null) txn.foreignApps = foreignApps;
if (foreignAssets != null) txn.foreignAssets = foreignAssets;
if (appBoxReferences != null) txn.boxReferences = convertBoxes(appBoxReferences, foreignApps, applicationId);
if (access != null) txn.access = access;
}

@Override
Expand Down Expand Up @@ -107,4 +145,29 @@ public T boxReferences(List<AppBoxReference> boxReferences) {
this.appBoxReferences = boxReferences;
return (T) this;
}

/**
* Set the access list for this transaction using low-level ResourceRef objects.
* The access list unifies accounts, foreignApps, foreignAssets, and boxReferences
* under a single list with explicit resource tracking.
*
* Note: Using the access field is mutually exclusive with using the separate accounts,
* foreignApps, foreignAssets, and boxReferences fields.
*/
public T access(List<ResourceRef> access) {
this.access = access;
return (T) this;
}

/**
* Set the access list for this transaction using high-level AppResourceRef objects.
* This provides a user-friendly API that automatically handles index conversion.
*
* Note: Using the access field is mutually exclusive with using the separate accounts,
* foreignApps, foreignAssets, and boxReferences fields.
*/
public T appResourceRefs(List<AppResourceRef> appResourceRefs) {
this.appResourceRefs = appResourceRefs;
return (T) this;
}
}
144 changes: 144 additions & 0 deletions src/main/java/com/algorand/algosdk/transaction/AccessConverter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
package com.algorand.algosdk.transaction;

import com.algorand.algosdk.crypto.Address;

import java.util.ArrayList;
import java.util.List;

/**
* AccessConverter handles the conversion from high-level AppResourceRef instances
* to index-based ResourceRef instances that go-algorand expects.
*
* This follows the same pattern as BoxReference.fromAppBoxReference() method.
*/
public class AccessConverter {

/**
* Convert a list of high-level AppResourceRef to index-based ResourceRef.
* This handles index 0 special cases and ensures proper referencing.
*
* @param appRefs High-level resource references
* @param sender Transaction sender (used for index 0 address references)
* @param currentAppId Current application ID (used for index 0 app references)
* @return List of index-based ResourceRef for serialization
*/
public static List<ResourceRef> convertToResourceRefs(
List<AppResourceRef> appRefs,
Address sender,
Long currentAppId) {

if (appRefs == null || appRefs.isEmpty()) {
return new ArrayList<>();
}

List<ResourceRef> result = new ArrayList<>();

// First pass: Create basic ResourceRef entries for addresses, assets, and apps
for (AppResourceRef appRef : appRefs) {
if (appRef instanceof AppResourceRef.AddressRef) {
AppResourceRef.AddressRef addrRef = (AppResourceRef.AddressRef) appRef;
result.add(ResourceRef.forAddress(addrRef.getAddress()));
} else if (appRef instanceof AppResourceRef.AssetRef) {
AppResourceRef.AssetRef assetRef = (AppResourceRef.AssetRef) appRef;
result.add(ResourceRef.forAsset(assetRef.getAssetId()));
} else if (appRef instanceof AppResourceRef.AppRef) {
AppResourceRef.AppRef appRefInner = (AppResourceRef.AppRef) appRef;
result.add(ResourceRef.forApp(appRefInner.getAppId()));
}
}

// Second pass: Handle compound references (holding, locals, box) with proper indices
for (AppResourceRef appRef : appRefs) {
if (appRef instanceof AppResourceRef.HoldingRef) {
AppResourceRef.HoldingRef holdingRef = (AppResourceRef.HoldingRef) appRef;
long addressIndex = findOrAddAddressIndex(
holdingRef.getAddress(), sender, result);
long assetIndex = findOrAddAssetIndex(
holdingRef.getAssetId(), result);
result.add(ResourceRef.forHolding(
new ResourceRef.HoldingRef(addressIndex, assetIndex)));

} else if (appRef instanceof AppResourceRef.LocalsRef) {
AppResourceRef.LocalsRef localsRef = (AppResourceRef.LocalsRef) appRef;
long addressIndex = findOrAddAddressIndex(
localsRef.getAddress(), sender, result);
long appIndex = findOrAddAppIndex(
localsRef.getAppId(), currentAppId, result);
result.add(ResourceRef.forLocals(
new ResourceRef.LocalsRef(addressIndex, appIndex)));

} else if (appRef instanceof AppResourceRef.BoxRef) {
AppResourceRef.BoxRef boxRef = (AppResourceRef.BoxRef) appRef;
long appIndex = findOrAddAppIndex(
boxRef.getAppId(), currentAppId, result);
result.add(ResourceRef.forBox(
new ResourceRef.BoxRef(appIndex, boxRef.getName())));
}
}

return result;
}

/**
* Find or add an address to the resource list and return its index.
* Handles index 0 special case (sender).
*/
private static long findOrAddAddressIndex(Address address, Address sender, List<ResourceRef> resources) {
// Special case: index 0 = sender
if (address == null || address.equals(sender)) {
return 0;
}

// Look for existing address in the list
for (int i = 0; i < resources.size(); i++) {
ResourceRef ref = resources.get(i);
if (ref.address != null && ref.address.equals(address)) {
return i + 1; // 1-based indexing (0 is special)
}
}

// Add address if not found
resources.add(ResourceRef.forAddress(address));
return resources.size(); // 1-based indexing
}

/**
* Find or add an asset to the resource list and return its index.
*/
private static long findOrAddAssetIndex(long assetId, List<ResourceRef> resources) {
// Look for existing asset in the list
for (int i = 0; i < resources.size(); i++) {
ResourceRef ref = resources.get(i);
if (ref.asset != null && ref.asset.equals(assetId)) {
return i + 1; // 1-based indexing
}
}

// Add asset if not found
resources.add(ResourceRef.forAsset(assetId));
return resources.size(); // 1-based indexing
}

/**
* Find or add an app to the resource list and return its index.
* Handles index 0 special case (current app).
*/
private static long findOrAddAppIndex(long appId, Long currentAppId, List<ResourceRef> resources) {
// Special case: index 0 = current app
if (currentAppId != null && appId == currentAppId) {
return 0;
}

// Look for existing app in the list
for (int i = 0; i < resources.size(); i++) {
ResourceRef ref = resources.get(i);
if (ref.app != null && ref.app.equals(appId)) {
return i + 1; // 1-based indexing (0 is special)
}
}

// Add app if not found
resources.add(ResourceRef.forApp(appId));
return resources.size(); // 1-based indexing
}
}
Loading