From e624bbb4429a8f6ba4b83dca2aed863f14c69010 Mon Sep 17 00:00:00 2001 From: Andreas Frank Date: Mon, 8 Sep 2025 11:37:38 +0300 Subject: [PATCH 1/4] Added docs for sdk4j --- docker-compose.yaml | 5 +- docs/MAIN_DOCUMENTATION.md | 818 +++++++++++++++++++++++++++++++ docs/MODEL_CLASSES_REFERENCE.md | 470 ++++++++++++++++++ docs/PROTOTYPE_CONTRACT_GUIDE.md | 355 ++++++++++++++ 4 files changed, 1645 insertions(+), 3 deletions(-) create mode 100644 docs/MAIN_DOCUMENTATION.md create mode 100644 docs/MODEL_CLASSES_REFERENCE.md create mode 100644 docs/PROTOTYPE_CONTRACT_GUIDE.md diff --git a/docker-compose.yaml b/docker-compose.yaml index 6536fb71..3592a97f 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,6 +1,6 @@ services: thor-solo: - image: vechain/thor:latest + image: ghcr.io/vechain/thor:darren-fix-packer-balance-check-0ffe8bccb7c6c8edd4364080bbcfba3c6e3b1964 hostname: thor-solo container_name: thor-solo user: root @@ -30,8 +30,7 @@ services: networks: - vechain-thor - networks: vechain-thor: driver: bridge - name: vechain-thor \ No newline at end of file + name: vechain-thor diff --git a/docs/MAIN_DOCUMENTATION.md b/docs/MAIN_DOCUMENTATION.md new file mode 100644 index 00000000..57b8d5d3 --- /dev/null +++ b/docs/MAIN_DOCUMENTATION.md @@ -0,0 +1,818 @@ +# VeChain Thor Client SDK for Java - Partner Integration Guide + +## Table of Contents +1. [Quick Start](#quick-start) +2. [Setup & Configuration](#setup--configuration) +3. [Blocks](#blocks) +4. [Transactions](#transactions) +5. [Accounts](#accounts) +6. [ERC20 Tokens](#erc20-tokens) +7. [Events & Logs](#events--logs) +8. [Fees](#fees) +9. [Subscriptions](#subscriptions) +10. [Multi-Party Payment (MPP)](#multi-party-payment-mpp) +11. [Error Handling](#error-handling) +12. [Best Practices](#best-practices) + +## Quick Start + +### Maven Dependency +```xml + + com.vechain + thor-client-sdk4j + 0.1.0 + +``` + +### Basic Setup +```java +import com.vechain.thorclient.core.model.blockchain.NodeProvider; + +// Configure node provider +NodeProvider nodeProvider = NodeProvider.getNodeProvider(); +nodeProvider.setProvider("https://mainnet.veblocks.net"); +nodeProvider.setTimeout(10000); +``` + +## Setup & Configuration + +### Node Provider Configuration +```java +// Mainnet +nodeProvider.setProvider("https://mainnet.veblocks.net"); + +// Testnet +nodeProvider.setProvider("https://testnet.veblocks.net"); + +// Local development +nodeProvider.setProvider("http://localhost:8669"); +``` + +### Wallet Creation & Management +```java +import com.vechain.thorclient.utils.WalletUtils; +import com.vechain.thorclient.utils.crypto.ECKeyPair; + +// Create new wallet +WalletInfo walletInfo = WalletUtils.createWallet("password123"); +String keyStore = walletInfo.toKeystoreString(); +ECKeyPair keyPair = walletInfo.getKeyPair(); + +// Load existing wallet +WalletInfo loadedWallet = WalletUtils.loadKeystore(keyStore, "password123"); +``` + +## Blocks + +### Overview +Blocks are the fundamental units of the VeChain blockchain, containing transactions and state changes. The SDK provides comprehensive block querying capabilities. + +### Data Types + +#### Block +Represents a complete blockchain block. + +**Fields**: +- `number`: Block number (string) +- `id`: Block ID (hex string) +- `size`: Block size in bytes +- `parentID`: Parent block ID +- `timestamp`: Block timestamp (Unix) +- `gasLimit`: Block gas limit +- `gasUsed`: Gas used in block +- `totalScore`: Cumulative difficulty +- `txsRoot`: Transactions merkle root +- `stateRoot`: State merkle root +- `receiptsRoot`: Receipts merkle root +- `signer`: Block signer address +- `beneficiary`: Block reward recipient +- `isTrunk`: Whether block is on main chain +- `transactions`: Array of transaction IDs or full transactions +- `baseFeePerGas`: Base fee per gas (Galactica) + +#### BlockRef +Block reference used for transaction construction. + +**Methods**: +- `toByteArray()`: Convert to 8-byte array for transactions + +#### Revision +Specifies which block to query. + +**Types**: +- `Revision.BEST`: Latest block +- `Revision.create(blockNumber)`: Specific block number +- `null`: Defaults to best block + +### Functions + +#### 1. Get Block +**Function**: `BlockClient.getBlock(Revision revision)` + +**Parameters**: +- `revision`: Block to retrieve (null for latest) + +**Returns**: `Block` object + +**Example**: +```java +// Get latest block +Block latestBlock = BlockClient.getBlock(null); +System.out.println("Latest block: " + latestBlock.getNumber()); +System.out.println("Block ID: " + latestBlock.getId()); +System.out.println("Timestamp: " + latestBlock.getTimestamp()); + +// Get specific block +Block block = BlockClient.getBlock(Revision.create(1000000)); +System.out.println("Block 1000000 signer: " + block.getSigner()); +``` + +#### 2. Get Expanded Block +**Function**: `BlockClient.getBlockExpanded(Revision revision)` + +**Parameters**: +- `revision`: Block to retrieve + +**Returns**: `Block` object with full transaction details + +**Example**: +```java +Block expandedBlock = BlockClient.getBlockExpanded(null); +System.out.println("Transactions in block: " + expandedBlock.getTransactions().size()); +``` + +#### 3. Get Chain Tag +**Function**: `BlockchainClient.getChainTag()` + +**Returns**: `byte` - Last byte of genesis block ID (chain identifier) + +**Example**: +```java +byte chainTag = BlockchainClient.getChainTag(); +System.out.println("Chain tag: " + chainTag); +// Mainnet: 39, Testnet: 39 +``` + +#### 4. Get Block Reference +**Function**: `BlockchainClient.getBlockRef(Revision revision)` + +**Parameters**: +- `revision`: Block to reference (null for best) + +**Returns**: `BlockRef` for transaction construction + +**Example**: +```java +BlockRef blockRef = BlockchainClient.getBlockRef(null); +byte[] refBytes = blockRef.toByteArray(); +// Use in transaction construction +``` + +#### 5. Get Peer Status +**Function**: `BlockchainClient.getPeerStatusList()` + +**Returns**: `PeerStatList` with connected node information + +**Example**: +```java +PeerStatList peers = BlockchainClient.getPeerStatusList(); +for (PeerStat peer : peers.getPeers()) { + System.out.println("Peer: " + peer.getName()); + System.out.println("Best block: " + peer.getBestBlockID()); +} +``` + +### Complete Block Example +```java +public class BlockExplorer { + public void exploreLatestBlock() throws ClientIOException { + // Get latest block + Block block = BlockClient.getBlock(null); + + System.out.println("=== Block Information ==="); + System.out.println("Number: " + block.getNumber()); + System.out.println("ID: " + block.getId()); + System.out.println("Size: " + block.getSize() + " bytes"); + System.out.println("Timestamp: " + new Date(block.getTimestamp() * 1000)); + System.out.println("Gas Used: " + block.getGasUsed() + "/" + block.getGasLimit()); + System.out.println("Signer: " + block.getSigner()); + System.out.println("Transaction count: " + block.getTransactions().size()); + + // Get block reference for transactions + BlockRef ref = block.blockRef(); + System.out.println("Block reference: " + BytesUtils.toHexString(ref.toByteArray())); + + // Check if this is the main chain + System.out.println("Is trunk: " + block.isTrunk()); + } +} +``` + +## Transactions + +### Overview +Transactions are state-changing operations on the VeChain blockchain. The SDK provides comprehensive transaction creation, signing, and querying capabilities. + +### Data Types + +#### Transaction +Complete transaction information. + +**Fields**: +- `id`: Transaction ID (hex string) +- `chainTag`: Chain identifier +- `blockRef`: Reference block (8 bytes) +- `expiration`: Block expiration +- `clauses`: Array of transaction clauses +- `gasPriceCoef`: Gas price coefficient +- `gas`: Gas limit +- `origin`: Transaction sender +- `delegator`: Fee delegator (if applicable) +- `size`: Transaction size +- `meta`: Transaction metadata +- `type`: Transaction type (0=legacy, 2=EIP-1559) +- `maxFeePerGas`: Maximum fee per gas (EIP-1559) +- `maxPriorityFeePerGas`: Maximum priority fee (EIP-1559) + +#### RawTransaction +Unsigned transaction data for construction. + +**Fields**: +- `chainTag`: Chain identifier +- `blockRef`: Reference block bytes +- `expiration`: Block expiration +- `clauses`: Transaction clauses +- `gasPriceCoef`: Gas price coefficient +- `gas`: Gas limit +- `dependsOn`: Transaction dependency +- `nonce`: Random nonce +- `signature`: Transaction signature +- `maxFeePerGas`: Maximum fee (EIP-1559) +- `maxPriorityFeePerGas`: Priority fee (EIP-1559) + +#### ToClause +Transaction clause specifying recipient, value, and data. + +**Constructor**: +```java +ToClause(Address to, Amount value, ToData data) +``` + +#### Receipt +Transaction execution result. + +**Fields**: +- `gasUsed`: Gas consumed +- `gasPayer`: Address that paid gas +- `paid`: Total VTHO paid +- `reward`: Block reward +- `reverted`: Whether execution failed +- `meta`: Receipt metadata +- `outputs`: Array of clause outputs +- `type`: Transaction type + +#### TransferResult +Result of transaction submission. + +**Fields**: +- `id`: Transaction ID + +### Functions + +#### 1. Get Transaction +**Function**: `TransactionClient.getTransaction(String txId, boolean isRaw, Revision revision)` + +**Parameters**: +- `txId`: Transaction ID (hex with 0x prefix) +- `isRaw`: Return raw transaction data +- `revision`: Block revision + +**Returns**: `Transaction` object + +**Example**: +```java +Transaction tx = TransactionClient.getTransaction( + "0x2c405851ca789f48c51c8ede5fadf682fc6636a9aa7ca366328332a3472326ae", + false, + null +); +System.out.println("Gas used: " + tx.getGas()); +System.out.println("Origin: " + tx.getOrigin()); +System.out.println("Clauses: " + tx.getClauses().length); +``` + +#### 2. Get Transaction Receipt +**Function**: `TransactionClient.getTransactionReceipt(String txId, Revision revision)` + +**Parameters**: +- `txId`: Transaction ID +- `revision`: Block revision + +**Returns**: `Receipt` object + +**Example**: +```java +Receipt receipt = TransactionClient.getTransactionReceipt( + "0x6b99c0f1ebfa3b9d93dcfc503f468104ac74271728841551aaa44115d080f5b5", + null +); +System.out.println("Gas used: " + receipt.getGasUsed()); +System.out.println("Reverted: " + receipt.isReverted()); +System.out.println("Events: " + receipt.getOutputs()[0].getEvents().size()); +``` + +#### 3. Build VET Transfer Clause +**Function**: `TransactionClient.buildVETToClause(Address toAddress, Amount amount, ToData data)` + +**Parameters**: +- `toAddress`: Recipient address +- `amount`: VET amount to transfer +- `data`: Additional data + +**Returns**: `ToClause` + +**Example**: +```java +ToClause clause = TransactionClient.buildVETToClause( + Address.fromHexString("0xRecipientAddress"), + Amount.createFromToken(AbstractToken.VET).setDecimalAmount("1.5"), + ToData.ZERO +); +``` + +#### 4. Transfer Transaction +**Function**: `TransactionClient.transfer(RawTransaction transaction)` + +**Parameters**: +- `transaction`: Signed raw transaction + +**Returns**: `TransferResult` + +**Example**: +```java +// Build transaction +ToClause clause = TransactionClient.buildVETToClause( + Address.fromHexString("0xRecipientAddress"), + Amount.createFromToken(AbstractToken.VET).setDecimalAmount("1.5"), + ToData.ZERO +); + +RawTransaction rawTx = RawTransactionFactory.getInstance().createRawTransaction( + BlockchainClient.getChainTag(), + BlockchainClient.getBlockRef(null).toByteArray(), + 720, // expiration (2 hours) + 21000, // gas limit + (byte) 0x0, // gas coefficient + CryptoUtils.generateTxNonce(), + clause +); + +// Sign and send +TransferResult result = TransactionClient.signThenTransfer(rawTx, keyPair); +System.out.println("Transaction ID: " + result.getId()); +``` + +#### 5. Sign Transaction +**Function**: `TransactionClient.sign(RawTransaction rawTransaction, ECKeyPair keyPair)` + +**Parameters**: +- `rawTransaction`: Unsigned transaction +- `keyPair`: Private key pair + +**Returns**: Signed `RawTransaction` + +#### 6. Deploy Contract +**Function**: `TransactionClient.deployContract(String contractHex, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +**Parameters**: +- `contractHex`: Contract bytecode +- `gas`: Gas limit +- `gasCoef`: Gas coefficient +- `expiration`: Block expiration +- `keyPair`: Deployer's key pair + +**Returns**: `TransferResult` + +**Example**: +```java +TransferResult result = TransactionClient.deployContract( + "0x608060405234801561001057600080fd5b50...", + 1000000, + (byte) 0, + 720, + keyPair +); +System.out.println("Contract deployed: " + result.getId()); +``` + +#### 7. EIP-1559 Contract Deployment +**Function**: `TransactionClient.deployContract(String contractHex, int gas, BigInteger maxPriorityFeePerGas, BigInteger maxFeePerGas, int expiration, ECKeyPair keyPair)` + +For Galactica dynamic fee transactions. + +### Complete Transaction Example +```java +public class TransactionManager { + private ECKeyPair keyPair; + + public String sendVET(String toAddress, String amount) throws ClientIOException { + // Build transaction clause + ToClause clause = TransactionClient.buildVETToClause( + Address.fromHexString(toAddress), + Amount.createFromToken(AbstractToken.VET).setDecimalAmount(amount), + ToData.ZERO + ); + + // Create raw transaction + RawTransaction rawTx = RawTransactionFactory.getInstance().createRawTransaction( + BlockchainClient.getChainTag(), + BlockchainClient.getBlockRef(null).toByteArray(), + 720, + 21000, + (byte) 0x0, + CryptoUtils.generateTxNonce(), + clause + ); + + // Sign and send + TransferResult result = TransactionClient.signThenTransfer(rawTx, keyPair); + + // Verify transaction ID matches + String calculatedId = BlockchainUtils.generateTransactionId( + rawTx, + Address.fromHexString(keyPair.getHexAddress()) + ); + assert result.getId().equals(calculatedId); + + return result.getId(); + } + + public void checkTransactionStatus(String txId) throws ClientIOException { + // Get transaction details + Transaction tx = TransactionClient.getTransaction(txId, false, null); + System.out.println("Transaction found in block: " + tx.getMeta().getBlockNumber()); + + // Get receipt for execution details + Receipt receipt = TransactionClient.getTransactionReceipt(txId, null); + System.out.println("Gas used: " + receipt.getGasUsed()); + System.out.println("Success: " + !receipt.isReverted()); + + if (receipt.getOutputs().length > 0) { + System.out.println("Events emitted: " + receipt.getOutputs()[0].getEvents().size()); + System.out.println("Transfers: " + receipt.getOutputs()[0].getTransfers().size()); + } + } +} +``` + +## Accounts + +### Overview +Accounts represent addresses on the VeChain blockchain, containing VET/VTHO balances and potentially smart contract code. + +### Data Types + +#### Account +Account state information. + +**Fields**: +- `balance`: VET balance (hex string in wei) +- `energy`: VTHO balance (hex string in wei) +- `hasCode`: Whether address contains contract code + +#### AccountCode +Contract bytecode at an address. + +**Fields**: +- `code`: Contract bytecode (hex string) + +#### AccountCall +Request for contract view function calls. + +**Fields**: +- `clauses`: Array of call clauses +- `caller`: Caller address +- `gas`: Gas limit +- `gasPrice`: Gas price + +#### AccountCallResult +Result of account call execution. + +**Fields**: +- `data`: Return data +- `events`: Emitted events +- `transfers`: Value transfers +- `gasUsed`: Gas consumed +- `reverted`: Execution status +- `vmError`: VM error message + +### Functions + +#### 1. Get Account Information +**Function**: `AccountClient.getAccountInfo(Address address, Revision revision)` + +**Parameters**: +- `address`: Account address to query +- `revision`: Block revision (null for latest) + +**Returns**: `Account` object + +**Example**: +```java +Account account = AccountClient.getAccountInfo( + Address.fromHexString("0xYourAddress"), + null +); +System.out.println("VET Balance: " + account.getBalance()); +System.out.println("VTHO Balance: " + account.getEnergy()); +System.out.println("Has Code: " + account.isHasCode()); +``` + +#### 2. Get Account Code +**Function**: `AccountClient.getAccountCode(Address address, Revision revision)` + +**Parameters**: +- `address`: Contract address +- `revision`: Block revision + +**Returns**: `AccountCode` object + +**Example**: +```java +AccountCode code = AccountClient.getAccountCode( + Address.VTHO_Address, + null +); +System.out.println("Contract code: " + code.getCode()); +``` + +#### 3. Perform Account Call +**Function**: `AccountClient.performAccountCall(Revision revision, AccountCall accountCall)` + +**Parameters**: +- `revision`: Block revision +- `accountCall`: Call specification + +**Returns**: `AccountCallResult` + +**Example**: +```java +AccountCall call = new AccountCall(); +ArrayList clauses = new ArrayList<>(); +clauses.add(new ToClause( + Address.VTHO_Address, + Amount.ZERO, + new ToData("0x70a08231000000000000000000000000" + "YourAddress") +)); +call.setClauses(clauses); + +AccountCallResult result = AccountClient.performAccountCall(null, call); +System.out.println("Call result: " + result.getData()); +``` + +#### 4. Get Storage Value +**Function**: `AccountClient.getStorageAt(Address address, StorageKey key, Revision revision)` + +**Parameters**: +- `address`: Contract address +- `key`: Storage key +- `revision`: Block revision + +**Returns**: `StorageData` + +## ERC20 Tokens + +### Overview +ERC20 tokens on VeChain, including the native VTHO token. The SDK provides specialized functions for token operations. + +### Data Types + +#### ERC20Token +Token specification. + +**Constants**: +- `ERC20Token.VTHO`: VTHO token contract +- `ERC20Token.VET`: VET compatibility token + +**Fields**: +- `contractAddress`: Token contract address +- `decimals`: Token decimal places +- `symbol`: Token symbol + +#### Amount +Token amount with decimal precision. + +**Methods**: +- `createFromToken(token)`: Create for specific token +- `setDecimalAmount(String)`: Set decimal amount +- `toBigInteger()`: Convert to wei +- `getDecimalAmount()`: Get decimal string + +### Functions + +#### 1. Get Token Balance +**Function**: `ERC20ContractClient.getERC20Balance(Address address, ERC20Token token, Revision revision)` + +**Parameters**: +- `address`: Token holder address +- `token`: ERC20Token specification +- `revision`: Block revision + +**Returns**: `Amount` object + +**Example**: +```java +Amount balance = ERC20ContractClient.getERC20Balance( + Address.fromHexString("0xYourAddress"), + ERC20Token.VTHO, + null +); +``` + +#### 2. Transfer Tokens (Legacy) +**Function**: `transferERC20Token(ERC20Token token, Address[] receivers, Amount[] amounts, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +#### 3. Transfer Tokens (EIP-1559) +**Function**: `transferERC20Token(ERC20Token token, Address[] receivers, Amount[] amounts, int gas, BigInteger maxFeePerGas, BigInteger maxPriorityFeePerGas, int expiration, ECKeyPair keyPair)` + +**Example**: +```java +TransferResult result = ERC20ContractClient.transferERC20Token( + ERC20Token.VTHO, + new Address[]{Address.fromHexString("0xRecipient")}, + new Amount[]{Amount.createFromToken(ERC20Token.VTHO).setDecimalAmount("100")}, + 80000, + new BigInteger("1000000000"), // maxFeePerGas + new BigInteger("1000000000"), // maxPriorityFeePerGas + 720, + keyPair +); +``` + +## Event & Log Monitoring + +### LogsClient Functions + +#### 1. Filter Event Logs +**Function**: `getFilteredLogEvents(LogFilter logFilter)` + +**Example**: +```java +LogFilter filter = new LogFilter(); +filter.setRange(Range.createBlockRange(1000, 2000)); +filter.setOptions(Options.create(0, 100)); + +ArrayList events = LogsClient.getFilteredLogEvents(filter); +``` + +#### 2. Filter Transfer Logs +**Function**: `getFilteredTransferLogs(TransferredFilter transferredFilter)` + +### SubscribeClient Functions + +#### 1. Subscribe to Blocks +**Function**: `subscribeBlock(BlockSubscribingRequest request, SubscribingCallback callback)` + +#### 2. Subscribe to Events +**Function**: `subscribeEvent(EventSubscribingRequest request, SubscribingCallback callback)` + +#### 3. Subscribe to Transfers +**Function**: `subscribeTransfer(TransferSubscribingRequest request, SubscribingCallback callback)` + +**Example**: +```java +SubscribeSocket socket = SubscribeClient.subscribeBlock( + null, // null for best blocks + new SubscribingCallback() { + @Override + public void onSubscribe(BlockSubscribingResponse response) { + System.out.println("New block: " + response.getNumber()); + } + + @Override + public void onError(Exception error) { + error.printStackTrace(); + } + } +); +``` + +## Fee Management + +### FeeClient Functions + +#### 1. Get Fee History +**Function**: `getFeeHistory(Number blockCount, String rewardPercentiles, String newestBlock)` + +**Example**: +```java +FeeHistoryResponse history = FeeClient.getFeeHistory( + 10, // last 10 blocks + "25,50,75", // percentiles + "latest" // newest block +); +``` + +#### 2. Get Priority Fee +**Function**: `getPriorityFee()` + +**Returns**: `BigInteger` - Suggested priority fee for next block inclusion + +## Error Handling + +### Common Exceptions + +- `ClientIOException`: Network or API errors +- `ClientArgumentException`: Invalid parameters + +**Example**: +```java +try { + Transaction tx = TransactionClient.getTransaction(txId, false, null); +} catch (ClientIOException e) { + // Handle network errors + logger.error("Network error: " + e.getMessage()); +} catch (ClientArgumentException e) { + // Handle invalid parameters + logger.error("Invalid argument: " + e.getMessage()); +} +``` + +## Best Practices + +### 1. Transaction Construction +- Always use current chain tag and block reference +- Set appropriate gas limits (21000 for VET transfers, 80000+ for contract calls) +- Use proper expiration values (720 blocks ≈ 2 hours) + +### 2. Fee Management +- For Galactica network, use EIP-1559 transactions with dynamic fees +- Query fee history for optimal fee estimation +- Use priority fees for faster transaction inclusion + +### 3. Error Handling +- Implement retry logic for network failures +- Validate addresses and amounts before transaction creation +- Check transaction receipts for execution status + +### 4. Performance +- Reuse NodeProvider instances +- Cache frequently accessed data (chain tag, block references) +- Use appropriate timeouts for network requests + +### 5. Security +- Never hardcode private keys +- Use secure key storage mechanisms +- Validate all user inputs before blockchain operations + +## Complete Integration Example + +```java +public class VeChainIntegration { + private static final String NODE_URL = "https://mainnet.veblocks.net"; + private ECKeyPair keyPair; + + public void initialize() { + // Setup node provider + NodeProvider.getNodeProvider().setProvider(NODE_URL); + NodeProvider.getNodeProvider().setTimeout(10000); + + // Load wallet + keyPair = loadWalletFromKeystore(); + } + + public String sendVET(String toAddress, String amount) throws ClientIOException { + // Build transaction clause + ToClause clause = TransactionClient.buildVETToClause( + Address.fromHexString(toAddress), + Amount.createFromToken(AbstractToken.VET).setDecimalAmount(amount), + ToData.ZERO + ); + + // Create raw transaction + RawTransaction rawTx = RawTransactionFactory.getInstance().createRawTransaction( + BlockchainClient.getChainTag(), + BlockchainClient.getBlockRef(null).toByteArray(), + 720, + 21000, + (byte) 0x0, + CryptoUtils.generateTxNonce(), + clause + ); + + // Sign and send + TransferResult result = TransactionClient.signThenTransfer(rawTx, keyPair); + return result.getId(); + } + + public Account getAccountInfo(String address) throws ClientIOException { + return AccountClient.getAccountInfo( + Address.fromHexString(address), + null + ); + } +} +``` + +This documentation provides comprehensive coverage of all SDK functions with practical examples for partner integration. diff --git a/docs/MODEL_CLASSES_REFERENCE.md b/docs/MODEL_CLASSES_REFERENCE.md new file mode 100644 index 00000000..92d883e2 --- /dev/null +++ b/docs/MODEL_CLASSES_REFERENCE.md @@ -0,0 +1,470 @@ +# VeChain Thor SDK - Model Classes Reference + +## Core Data Types + +### Address +Represents a VeChain address. + +**Methods**: +- `fromHexString(String hex)`: Create from hex string +- `toHexString(Prefix prefix)`: Convert to hex string +- `getBytes()`: Get raw bytes + +**Constants**: +- `Address.VTHO_Address`: VTHO token contract address +- `Address.NULL_ADDRESS`: Zero address + +### Amount +Represents token amounts with decimal precision. + +**Methods**: +- `createFromToken(AbstractToken token)`: Create for specific token +- `setDecimalAmount(String amount)`: Set decimal amount +- `toBigInteger()`: Convert to BigInteger (wei) +- `getDecimalAmount()`: Get decimal representation + +### Revision +Represents block revision for queries. + +**Static Methods**: +- `Revision.BEST`: Latest block +- `Revision.create(long blockNumber)`: Specific block number + +## Transaction Models + +### RawTransaction +Unsigned transaction data. + +**Fields**: +- `chainTag`: Chain identifier +- `blockRef`: Reference block +- `expiration`: Block expiration +- `clauses`: Transaction clauses +- `gasPriceCoef`: Gas price coefficient +- `gas`: Gas limit +- `dependsOn`: Transaction dependency +- `nonce`: Transaction nonce +- `signature`: Transaction signature + +### ToClause +Transaction clause specifying recipient, value, and data. + +**Constructor**: +```java +ToClause(Address to, Amount value, ToData data) +``` + +### ToData +Transaction data payload. + +**Methods**: +- `ToData.ZERO`: Empty data +- `setData(String hexData)`: Set hex data + +### TransferResult +Result of transaction submission. + +**Fields**: +- `id`: Transaction ID +- `success`: Success status + +### Transaction +Complete transaction information. + +**Fields**: +- `id`: Transaction ID +- `chainTag`: Chain tag +- `blockRef`: Block reference +- `expiration`: Expiration +- `clauses`: Transaction clauses +- `gasPriceCoef`: Gas price coefficient +- `gas`: Gas limit +- `origin`: Transaction origin +- `delegator`: Delegator address (if applicable) +- `size`: Transaction size +- `meta`: Transaction metadata + +### Receipt +Transaction execution receipt. + +**Fields**: +- `gasUsed`: Gas consumed +- `gasPayer`: Address that paid gas +- `paid`: Total payment +- `reward`: Block reward +- `reverted`: Execution status +- `meta`: Receipt metadata +- `outputs`: Transaction outputs + +## Block Models + +### Block +Blockchain block information. + +**Fields**: +- `number`: Block number +- `id`: Block ID +- `size`: Block size +- `parentID`: Parent block ID +- `timestamp`: Block timestamp +- `gasLimit`: Gas limit +- `gasUsed`: Gas used +- `totalScore`: Total score +- `txsRoot`: Transactions root +- `stateRoot`: State root +- `receiptsRoot`: Receipts root +- `signer`: Block signer +- `beneficiary`: Beneficiary address +- `isTrunk`: Trunk status +- `transactions`: Transaction list + +**Methods**: +- `blockRef()`: Get BlockRef for transactions + +### BlockRef +Block reference for transaction construction. + +**Methods**: +- `toByteArray()`: Convert to byte array + +## Account Models + +### Account +Account state information. + +**Fields**: +- `balance`: VET balance (hex string) +- `energy`: VTHO balance (hex string) +- `hasCode`: Contract indicator + +### AccountCode +Contract bytecode information. + +**Fields**: +- `code`: Contract bytecode (hex string) + +### AccountCall +Account call request for contract interaction. + +**Fields**: +- `clauses`: Call clauses +- `caller`: Caller address +- `gas`: Gas limit +- `gasPrice`: Gas price + +### AccountCallResult +Result of account call. + +**Fields**: +- `data`: Return data +- `events`: Emitted events +- `transfers`: Value transfers +- `gasUsed`: Gas consumed +- `reverted`: Execution status +- `vmError`: VM error message + +## Contract Models + +### ContractCall +Contract method call specification. + +**Fields**: +- `data`: Call data (hex string) +- `value`: Value to send + +### ContractCallResult +Contract call execution result. + +**Fields**: +- `data`: Return data +- `events`: Emitted events +- `transfers`: Value transfers +- `gasUsed`: Gas consumed +- `reverted`: Execution status +- `vmError`: VM error message + +**Methods**: +- `getBalance(ERC20Token token)`: Extract token balance + +## Event and Log Models + +### Event +Blockchain event log. + +**Fields**: +- `address`: Contract address +- `topics`: Event topics +- `data`: Event data + +### FilteredEvent +Filtered event with metadata. + +**Fields**: +- `address`: Contract address +- `topics`: Event topics +- `data`: Event data +- `meta`: Event metadata + +### FilteredLogEvent +Log event with filtering metadata. + +**Fields**: +- `address`: Contract address +- `topics`: Event topics +- `data`: Event data +- `meta`: Log metadata + +### EventFilter +Event filtering criteria. + +**Fields**: +- `range`: Block range +- `options`: Pagination options +- `criteriaSet`: Filter criteria + +### LogFilter +Log filtering specification. + +**Fields**: +- `range`: Block range +- `options`: Pagination options +- `criteriaSet`: Filter criteria + +## Transfer Models + +### FilteredTransfer +VET transfer with metadata. + +**Fields**: +- `sender`: Sender address +- `recipient`: Recipient address +- `amount`: Transfer amount +- `meta`: Transfer metadata + +### FilteredTransferEvent +Transfer event with metadata. + +**Fields**: +- `sender`: Sender address +- `recipient`: Recipient address +- `amount`: Transfer amount +- `meta`: Event metadata + +### TransferFilter +Transfer filtering criteria. + +**Fields**: +- `range`: Block range +- `options`: Pagination options +- `criteriaSet`: Address criteria + +## Fee Models + +### FeeHistoryResponse +Historical fee data. + +**Fields**: +- `oldestBlock`: Oldest block in range +- `baseFeePerGas`: Base fees per block +- `gasUsedRatio`: Gas usage ratios +- `reward`: Priority fee percentiles + +### MaxPriorityFeeResponse +Priority fee recommendation. + +**Fields**: +- `maxPriorityFeePerGas`: Recommended priority fee + +## Subscription Models + +### BlockSubscribingRequest +Block subscription parameters. + +**Fields**: +- `pos`: Starting position + +### BlockSubscribingResponse +Block subscription notification. + +**Fields**: +- `number`: Block number +- `id`: Block ID +- `size`: Block size +- `parentID`: Parent block ID +- `timestamp`: Block timestamp +- `gasLimit`: Gas limit +- `gasUsed`: Gas used +- `totalScore`: Total score +- `txsRoot`: Transactions root +- `stateRoot`: State root +- `receiptsRoot`: Receipts root +- `signer`: Block signer +- `beneficiary`: Beneficiary address +- `obsolete`: Obsolete flag + +### EventSubscribingRequest +Event subscription parameters. + +**Fields**: +- `pos`: Starting position +- `addr`: Contract address +- `t0`, `t1`, `t2`, `t3`, `t4`: Topic filters + +### EventSubscribingResponse +Event subscription notification. + +**Fields**: +- `address`: Contract address +- `topics`: Event topics +- `data`: Event data +- `meta`: Event metadata +- `obsolete`: Obsolete flag + +### TransferSubscribingRequest +Transfer subscription parameters. + +**Fields**: +- `pos`: Starting position +- `txOrigin`: Transaction origin +- `sender`: Transfer sender +- `recipient`: Transfer recipient + +### TransferSubscribingResponse +Transfer subscription notification. + +**Fields**: +- `sender`: Sender address +- `recipient`: Recipient address +- `amount`: Transfer amount +- `meta`: Transfer metadata +- `obsolete`: Obsolete flag + +## Utility Models + +### Range +Block range specification. + +**Static Methods**: +- `createBlockRange(long from, long to)`: Create block range +- `createTimeRange(long from, long to)`: Create time range + +### Options +Pagination options. + +**Static Methods**: +- `create(int offset, int limit)`: Create pagination options + +### Order +Result ordering specification. + +**Values**: +- `Order.ASC`: Ascending order +- `Order.DESC`: Descending order + +## Token Models + +### ERC20Token +ERC20 token specification. + +**Constants**: +- `ERC20Token.VTHO`: VTHO token +- `ERC20Token.VET`: VET token (for compatibility) + +**Fields**: +- `contractAddress`: Token contract address +- `decimals`: Token decimals +- `symbol`: Token symbol + +### AbstractToken +Base token interface. + +**Constants**: +- `AbstractToken.VET`: Native VET token + +## Error Models + +### ClientIOException +Network and I/O related errors. + +### ClientArgumentException +Invalid parameter errors. + +## Node Models + +### NodeProvider +Node connection configuration. + +**Methods**: +- `getNodeProvider()`: Get singleton instance +- `setProvider(String url)`: Set node URL +- `setTimeout(int timeout)`: Set request timeout +- `getProvider()`: Get current provider URL +- `getWsProvider()`: Get WebSocket provider URL + +### PeerStat +Node peer statistics. + +**Fields**: +- `name`: Peer name +- `bestBlockID`: Best block ID +- `totalScore`: Total score +- `peerID`: Peer identifier +- `netAddr`: Network address +- `inbound`: Connection direction +- `duration`: Connection duration + +### PeerStatList +Collection of peer statistics. + +**Fields**: +- `peers`: List of peer stats + +## Usage Examples + +### Creating Transaction Clauses +```java +// VET transfer clause +ToClause vetClause = new ToClause( + Address.fromHexString("0xRecipient"), + Amount.createFromToken(AbstractToken.VET).setDecimalAmount("1.5"), + ToData.ZERO +); + +// Contract call clause +ToData callData = new ToData(); +callData.setData("0xa9059cbb000000000000000000000000..."); +ToClause contractClause = new ToClause( + Address.fromHexString("0xContractAddress"), + Amount.ZERO, + callData +); +``` + +### Filtering Events +```java +EventFilter filter = new EventFilter(); +filter.setRange(Range.createBlockRange(1000, 2000)); +filter.setOptions(Options.create(0, 100)); + +// Add topic filters +EventCriteria criteria = new EventCriteria(); +criteria.setAddress(Address.fromHexString("0xContractAddress")); +criteria.setTopic0("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); +filter.addCriteria(criteria); +``` + +### Working with Amounts +```java +// Create VET amount +Amount vetAmount = Amount.createFromToken(AbstractToken.VET); +vetAmount.setDecimalAmount("10.5"); + +// Create VTHO amount +Amount vthoAmount = Amount.createFromToken(ERC20Token.VTHO); +vthoAmount.setDecimalAmount("1000"); + +// Convert to wei +BigInteger weiValue = vetAmount.toBigInteger(); +``` + +This reference covers all major model classes used throughout the VeChain Thor SDK. diff --git a/docs/PROTOTYPE_CONTRACT_GUIDE.md b/docs/PROTOTYPE_CONTRACT_GUIDE.md new file mode 100644 index 00000000..0c6d0fb1 --- /dev/null +++ b/docs/PROTOTYPE_CONTRACT_GUIDE.md @@ -0,0 +1,355 @@ +# ProtoType Contract Client - Multi-Party Payment (MPP) Guide + +## Overview + +The ProtoType Contract is VeChain's native contract for Multi-Party Payment (MPP), enabling scenarios where transaction fees can be paid by a different party than the transaction sender. This is useful for dApps that want to sponsor user transactions or implement credit-based payment systems. + +## Core Concepts + +### Roles +- **Master**: Controls user management and credit plans for a target address +- **User**: Can send transactions with fees paid by the target address +- **Sponsor**: Provides VTHO to cover transaction fees +- **Target**: The address that receives transactions and may pay fees + +### Workflow +1. Set a master for target addresses +2. Add users to the target's user plan +3. Set credit plans (credit amount and recovery rate) +4. Users can now send transactions with fees deducted from target's credit + +## ProtoTypeContractClient Functions + +### 1. Master Management + +#### Get Master Address +**Function**: `getMasterAddress(Address target, Revision revision)` + +**Parameters**: +- `target`: Target address to query +- `revision`: Block revision (null for latest) + +**Returns**: `ContractCallResult` containing master address + +**Example**: +```java +ContractCallResult result = ProtoTypeContractClient.getMasterAddress( + Address.fromHexString("0xTargetAddress"), + null +); +``` + +#### Set Master Address +**Function**: `setMasterAddress(Address[] targets, Address[] newMasters, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +**Parameters**: +- `targets`: Array of target addresses +- `newMasters`: Array of new master addresses +- `gas`: Gas limit +- `gasCoef`: Gas coefficient +- `expiration`: Transaction expiration +- `keyPair`: Current owner/master's key pair + +**Returns**: `TransferResult` + +**Example**: +```java +TransferResult result = ProtoTypeContractClient.setMasterAddress( + new Address[]{Address.fromHexString("0xTargetAddress")}, + new Address[]{Address.fromHexString("0xNewMasterAddress")}, + 100000, + (byte) 0, + 720, + masterKeyPair +); +``` + +### 2. User Management + +#### Add Users +**Function**: `addUsers(Address[] targets, Address[] users, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +**Parameters**: +- `targets`: Target addresses +- `users`: User addresses to add +- `gas`: Gas limit +- `gasCoef`: Gas coefficient +- `expiration`: Transaction expiration +- `keyPair`: Master's key pair + +**Example**: +```java +TransferResult result = ProtoTypeContractClient.addUsers( + new Address[]{Address.fromHexString("0xTargetAddress")}, + new Address[]{Address.fromHexString("0xUserAddress")}, + 100000, + (byte) 0, + 720, + masterKeyPair +); +``` + +#### Remove Users +**Function**: `removeUsers(Address[] targets, Address[] users, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +Similar to `addUsers` but removes users from the target's user plan. + +#### Check if User +**Function**: `isUser(Address target, Address user, Revision revision)` + +**Returns**: `ContractCallResult` with boolean indicating if address is a user + +**Example**: +```java +ContractCallResult result = ProtoTypeContractClient.isUser( + Address.fromHexString("0xTargetAddress"), + Address.fromHexString("0xUserAddress"), + null +); +``` + +### 3. Credit Plan Management + +#### Set Credit Plans +**Function**: `setCreditPlans(Address[] targets, Amount[] credits, Amount[] recoveryRates, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +**Parameters**: +- `targets`: Target addresses +- `credits`: Credit amounts (in VTHO wei) +- `recoveryRates`: Recovery rates (VTHO per second) +- `gas`: Gas limit +- `gasCoef`: Gas coefficient +- `expiration`: Transaction expiration +- `keyPair`: Master's key pair + +**Example**: +```java +Amount credit = Amount.createFromToken(ERC20Token.VTHO); +credit.setDecimalAmount("1000"); // 1000 VTHO credit + +Amount recoveryRate = Amount.createFromToken(ERC20Token.VTHO); +recoveryRate.setDecimalAmount("0.1"); // 0.1 VTHO per second recovery + +TransferResult result = ProtoTypeContractClient.setCreditPlans( + new Address[]{Address.fromHexString("0xTargetAddress")}, + new Amount[]{credit}, + new Amount[]{recoveryRate}, + 100000, + (byte) 0, + 720, + masterKeyPair +); +``` + +#### Get Credit Plan +**Function**: `getCreditPlan(Address target, Revision revision)` + +**Returns**: `ContractCallResult` with credit plan details + +#### Get User Credit +**Function**: `getUserCredit(Address target, Address user, Revision revision)` + +**Returns**: `ContractCallResult` with current user credit + +**Example**: +```java +ContractCallResult result = ProtoTypeContractClient.getUserCredit( + Address.fromHexString("0xTargetAddress"), + Address.fromHexString("0xUserAddress"), + null +); +``` + +### 4. Sponsorship Management + +#### Sponsor Address +**Function**: `sponsor(Address[] targets, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +**Parameters**: +- `targets`: Addresses to sponsor +- `gas`: Gas limit +- `gasCoef`: Gas coefficient +- `expiration`: Transaction expiration +- `keyPair`: Sponsor's key pair + +**Example**: +```java +TransferResult result = ProtoTypeContractClient.sponsor( + new Address[]{Address.fromHexString("0xTargetAddress")}, + 100000, + (byte) 0, + 720, + sponsorKeyPair +); +``` + +#### Unsponsor Address +**Function**: `unsponsor(Address[] targets, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +Removes sponsorship from target addresses. + +#### Select Sponsor +**Function**: `selectSponsor(Address[] targets, Address[] sponsors, int gas, byte gasCoef, int expiration, ECKeyPair keyPair)` + +**Parameters**: +- `targets`: Target addresses +- `sponsors`: Sponsor addresses to select +- `gas`: Gas limit +- `gasCoef`: Gas coefficient +- `expiration`: Transaction expiration +- `keyPair`: Master's key pair + +#### Get Current Sponsor +**Function**: `getCurrentSponsor(Address target, Revision revision)` + +**Returns**: `ContractCallResult` with current sponsor address + +#### Check if Sponsor +**Function**: `isSponsor(Address target, Address sponsor, Revision revision)` + +**Returns**: `ContractCallResult` with boolean indicating sponsorship status + +## Complete MPP Implementation Example + +```java +public class MPPImplementation { + private ECKeyPair masterKeyPair; + private ECKeyPair sponsorKeyPair; + private ECKeyPair userKeyPair; + + public void setupMPP() throws ClientIOException { + Address targetAddress = Address.fromHexString("0xTargetAddress"); + Address userAddress = Address.fromHexString("0xUserAddress"); + Address sponsorAddress = Address.fromHexString("0xSponsorAddress"); + + // Step 1: Set master (if not already set) + TransferResult masterResult = ProtoTypeContractClient.setMasterAddress( + new Address[]{targetAddress}, + new Address[]{Address.fromHexString("0xMasterAddress")}, + 100000, + (byte) 0, + 720, + masterKeyPair + ); + + // Step 2: Add user to target's user plan + TransferResult userResult = ProtoTypeContractClient.addUsers( + new Address[]{targetAddress}, + new Address[]{userAddress}, + 100000, + (byte) 0, + 720, + masterKeyPair + ); + + // Step 3: Set credit plan + Amount credit = Amount.createFromToken(ERC20Token.VTHO); + credit.setDecimalAmount("1000"); // 1000 VTHO credit + + Amount recoveryRate = Amount.createFromToken(ERC20Token.VTHO); + recoveryRate.setDecimalAmount("0.1"); // 0.1 VTHO per second + + TransferResult creditResult = ProtoTypeContractClient.setCreditPlans( + new Address[]{targetAddress}, + new Amount[]{credit}, + new Amount[]{recoveryRate}, + 100000, + (byte) 0, + 720, + masterKeyPair + ); + + // Step 4: Sponsor the target address + TransferResult sponsorResult = ProtoTypeContractClient.sponsor( + new Address[]{targetAddress}, + 100000, + (byte) 0, + 720, + sponsorKeyPair + ); + + // Step 5: Select the sponsor + TransferResult selectResult = ProtoTypeContractClient.selectSponsor( + new Address[]{targetAddress}, + new Address[]{sponsorAddress}, + 100000, + (byte) 0, + 720, + masterKeyPair + ); + } + + public void checkMPPStatus(Address targetAddress, Address userAddress) throws ClientIOException { + // Check if user is registered + ContractCallResult isUserResult = ProtoTypeContractClient.isUser( + targetAddress, userAddress, null + ); + + // Get user's current credit + ContractCallResult creditResult = ProtoTypeContractClient.getUserCredit( + targetAddress, userAddress, null + ); + + // Get credit plan + ContractCallResult planResult = ProtoTypeContractClient.getCreditPlan( + targetAddress, null + ); + + // Get current sponsor + ContractCallResult sponsorResult = ProtoTypeContractClient.getCurrentSponsor( + targetAddress, null + ); + + System.out.println("User registered: " + isUserResult.getData()); + System.out.println("Current credit: " + creditResult.getData()); + System.out.println("Credit plan: " + planResult.getData()); + System.out.println("Current sponsor: " + sponsorResult.getData()); + } +} +``` + +## Use Cases + +### 1. dApp User Onboarding +- dApp sponsors new users by covering their transaction fees +- Users can interact with the dApp without holding VTHO +- Gradual transition to self-paying as users become engaged + +### 2. Enterprise B2B Payments +- Company sets up MPP for employee transactions +- Employees can send transactions with company paying fees +- Credit limits and recovery rates control spending + +### 3. Gaming Applications +- Game sponsors player transactions for better UX +- Players can perform in-game actions without gas fees +- Credit system prevents abuse while maintaining engagement + +### 4. Subscription Services +- Service provider sponsors subscriber transactions +- Subscribers get allocated credits based on subscription tier +- Automatic credit recovery ensures continuous service + +## Best Practices + +### 1. Credit Management +- Set appropriate credit limits based on expected usage +- Use recovery rates to prevent credit exhaustion +- Monitor credit usage and adjust plans as needed + +### 2. Security +- Carefully manage master key pairs +- Regularly audit user lists and credit allocations +- Implement monitoring for unusual spending patterns + +### 3. Gas Optimization +- Batch operations when adding/removing multiple users +- Use appropriate gas limits for contract calls +- Consider gas costs when setting credit plans + +### 4. Monitoring +- Track credit usage patterns +- Monitor sponsor VTHO balances +- Set up alerts for low credit situations + +This guide provides comprehensive coverage of the ProtoType Contract functionality for implementing Multi-Party Payment solutions. From 8e8a4198c94d0f36e506b0fca7280eda7cb396bb Mon Sep 17 00:00:00 2001 From: Andreas Frank Date: Mon, 8 Sep 2025 11:58:03 +0300 Subject: [PATCH 2/4] Added javadocs for sdk4j --- .../thorclient/clients/AccountClient.java | 73 ++++++++++++++-- .../thorclient/clients/BlockClient.java | 83 +++++++++++++++++-- .../clients/ERC20ContractClient.java | 74 +++++++++++++++-- .../thorclient/clients/TransactionClient.java | 78 +++++++++++++++-- .../core/model/clients/Address.java | 42 +++++++++- .../thorclient/core/model/clients/Amount.java | 40 ++++++++- 6 files changed, 358 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/vechain/thorclient/clients/AccountClient.java b/src/main/java/com/vechain/thorclient/clients/AccountClient.java index 91adfaa6..d77c0276 100644 --- a/src/main/java/com/vechain/thorclient/clients/AccountClient.java +++ b/src/main/java/com/vechain/thorclient/clients/AccountClient.java @@ -9,18 +9,77 @@ import java.util.HashMap; /** - * Accounts module client. It can get Account, + * AccountClient provides access to VeChain blockchain account information and operations. + * + *

Accounts represent addresses on the VeChain blockchain, containing VET/VTHO balances + * and potentially smart contract code. This client provides comprehensive account querying + * capabilities including balance checks, contract code retrieval, and contract calls.

+ * + *

Account Information

+ *

Each account contains:

+ *
    + *
  • balance: VET balance (hex string in wei)
  • + *
  • energy: VTHO balance (hex string in wei)
  • + *
  • hasCode: Whether address contains contract code
  • + *
+ * + *

Usage Examples

+ *
{@code
+ * // Get account information
+ * Account account = AccountClient.getAccountInfo(
+ *     Address.fromHexString("0xYourAddress"),
+ *     null
+ * );
+ * System.out.println("VET Balance: " + account.getBalance());
+ * System.out.println("VTHO Balance: " + account.getEnergy());
+ * System.out.println("Has Code: " + account.isHasCode());
+ * 
+ * // Get contract code
+ * AccountCode code = AccountClient.getAccountCode(
+ *     Address.VTHO_Address,
+ *     null
+ * );
+ * System.out.println("Contract code: " + code.getCode());
+ * 
+ * // Perform contract call
+ * AccountCall call = new AccountCall();
+ * ArrayList clauses = new ArrayList<>();
+ * clauses.add(new ToClause(
+ *     Address.VTHO_Address,
+ *     Amount.ZERO,
+ *     new ToData("0x70a08231000000000000000000000000" + "YourAddress")
+ * ));
+ * call.setClauses(clauses);
+ * 
+ * AccountCallResult result = AccountClient.performAccountCall(null, call);
+ * System.out.println("Call result: " + result.getData());
+ * }
+ * + * @see Account + * @see AccountCode + * @see AccountCall + * @see AccountCallResult + * @since 0.1.0 */ public class AccountClient extends AbstractClient { /** - * Get Account Info. + * Retrieves account information including VET/VTHO balances and contract status. * - * @param address required, if null will throw the - * {@link ClientArgumentException}. - * @param revision block revision. - * @return {@link Account} - * @throws ClientIOException if network error or invalid request. + *

Returns comprehensive account state information including native VET balance, + * VTHO energy balance, and whether the address contains smart contract code.

+ * + * @param address the account address to query. Must not be {@code null} + * @param revision the block revision for the query. Use {@code null} for latest block, + * {@link Revision#BEST} for best block, or {@link Revision#create(long)} + * for a specific block number + * @return the account information including balances and contract status + * @throws ClientIOException if there's a network error or the request fails + * @throws ClientArgumentException if the address is {@code null} + * + * @see Account + * @see Revision#BEST + * @see Revision#create(long) */ public static Account getAccountInfo(Address address, Revision revision) throws ClientIOException { diff --git a/src/main/java/com/vechain/thorclient/clients/BlockClient.java b/src/main/java/com/vechain/thorclient/clients/BlockClient.java index 31632a06..0be23d7d 100644 --- a/src/main/java/com/vechain/thorclient/clients/BlockClient.java +++ b/src/main/java/com/vechain/thorclient/clients/BlockClient.java @@ -7,14 +7,67 @@ import java.util.HashMap; +/** + * BlockClient provides access to VeChain blockchain block information. + * + *

Blocks are the fundamental units of the VeChain blockchain, containing transactions + * and state changes. This client provides comprehensive block querying capabilities.

+ * + *

Block Structure

+ *

Each block contains:

+ *
    + *
  • number: Block number (string)
  • + *
  • id: Block ID (hex string)
  • + *
  • size: Block size in bytes
  • + *
  • parentID: Parent block ID
  • + *
  • timestamp: Block timestamp (Unix)
  • + *
  • gasLimit: Block gas limit
  • + *
  • gasUsed: Gas used in block
  • + *
  • totalScore: Cumulative difficulty
  • + *
  • signer: Block signer address
  • + *
  • beneficiary: Block reward recipient
  • + *
  • isTrunk: Whether block is on main chain
  • + *
  • transactions: Array of transaction IDs or full transactions
  • + *
+ * + *

Usage Examples

+ *
{@code
+ * // Get latest block
+ * Block latestBlock = BlockClient.getBlock(null);
+ * System.out.println("Latest block: " + latestBlock.getNumber());
+ * System.out.println("Block ID: " + latestBlock.getId());
+ * System.out.println("Timestamp: " + latestBlock.getTimestamp());
+ * 
+ * // Get specific block
+ * Block block = BlockClient.getBlock(Revision.create(1000000));
+ * System.out.println("Block 1000000 signer: " + block.getSigner());
+ * 
+ * // Get block with full transaction details
+ * Block expandedBlock = BlockClient.getBlockExpanded(null);
+ * System.out.println("Transactions in block: " + expandedBlock.getTransactions().size());
+ * }
+ * + * @see Block + * @see Revision + * @since 0.1.0 + */ public class BlockClient extends AbstractClient { /** - * Get {@link Block} information. + * Retrieves block information from the VeChain blockchain. * - * @param revision {@link Revision} optional the block revision, can be null. - * @return Block {@link Block} can be null. - * @throws ClientIOException + *

Returns basic block information including header data, transaction IDs, + * and block metadata. For full transaction details, use {@link #getBlockExpanded(Revision)}.

+ * + * @param revision the block revision to query. Use {@code null} for the latest block, + * {@link Revision#BEST} for the best block, or {@link Revision#create(long)} + * for a specific block number + * @return the block information, or {@code null} if the block doesn't exist + * @throws ClientIOException if there's a network error or the request fails + * + * @see #getBlockExpanded(Revision) + * @see Revision#BEST + * @see Revision#create(long) */ public static Block getBlock(Revision revision) throws ClientIOException { Revision currentRevision = revision; @@ -27,11 +80,25 @@ public static Block getBlock(Revision revision) throws ClientIOException { } /** - * Get {@link Block} information expanded. + * Retrieves expanded block information with full transaction details. + * + *

Returns complete block information including full transaction objects rather than + * just transaction IDs. This provides detailed information about all transactions + * within the block, including clauses, gas usage, and execution results.

+ * + *

Note: This method returns more data than {@link #getBlock(Revision)} + * and may take longer to execute for blocks with many transactions.

+ * + * @param revision the block revision to query. Use {@code null} for the latest block, + * {@link Revision#BEST} for the best block, or {@link Revision#create(long)} + * for a specific block number + * @return the expanded block information with full transaction details, + * or {@code null} if the block doesn't exist + * @throws ClientIOException if there's a network error or the request fails * - * @param revision {@link Revision} optional the block revision, can be null. - * @return Block {@link Block} can be null. - * @throws ClientIOException + * @see #getBlock(Revision) + * @see Revision#BEST + * @see Revision#create(long) */ public static Block getBlockExpanded(Revision revision) throws ClientIOException { Revision currentRevision = revision; diff --git a/src/main/java/com/vechain/thorclient/clients/ERC20ContractClient.java b/src/main/java/com/vechain/thorclient/clients/ERC20ContractClient.java index f8c30594..8524daa5 100644 --- a/src/main/java/com/vechain/thorclient/clients/ERC20ContractClient.java +++ b/src/main/java/com/vechain/thorclient/clients/ERC20ContractClient.java @@ -16,17 +16,75 @@ import java.math.BigInteger; import java.util.ArrayList; +/** + * ERC20ContractClient provides specialized operations for ERC20 token contracts on VeChain. + * + *

This client extends TransactionClient to provide convenient methods for interacting with + * ERC20 token contracts, including balance queries and token transfers. It supports both the + * native VTHO token and custom ERC20 tokens deployed on VeChain.

+ * + *

Supported Tokens

+ *
    + *
  • VTHO: Native VeChain energy token ({@link ERC20Token#VTHO})
  • + *
  • Custom ERC20: Any ERC20-compliant token contract
  • + *
+ * + *

Transaction Types

+ *

Supports both legacy and EIP-1559 (Galactica) transaction types:

+ *
    + *
  • Legacy: Uses gas price coefficient
  • + *
  • EIP-1559: Uses maxFeePerGas and maxPriorityFeePerGas
  • + *
+ * + *

Usage Examples

+ *
{@code
+ * // Get VTHO balance
+ * Amount balance = ERC20ContractClient.getERC20Balance(
+ *     Address.fromHexString("0xYourAddress"),
+ *     ERC20Token.VTHO,
+ *     null
+ * );
+ * System.out.println("VTHO Balance: " + balance.getDecimalAmount());
+ * 
+ * // Transfer VTHO tokens (EIP-1559)
+ * TransferResult result = ERC20ContractClient.transferERC20Token(
+ *     ERC20Token.VTHO,
+ *     new Address[]{Address.fromHexString("0xRecipient")},
+ *     new Amount[]{Amount.createFromToken(ERC20Token.VTHO).setDecimalAmount("100")},
+ *     80000,
+ *     new BigInteger("1000000000"), // maxFeePerGas
+ *     new BigInteger("1000000000"), // maxPriorityFeePerGas
+ *     720,
+ *     keyPair
+ * );
+ * System.out.println("Transfer TX: " + result.getId());
+ * }
+ * + * @see ERC20Token + * @see Amount + * @see TransactionClient + * @since 0.1.0 + */ public class ERC20ContractClient extends TransactionClient { /** - * Get amount from ERC20 contract. - * - * @param address address of token holder. - * @param token {@link ERC20Token} required, the token {@link ERC20Token} - * @param revision {@link Revision} if it is null, it will fallback to default - * {@link Revision#BEST} - * @return {@link Amount} - * @throws ClientIOException {@link ClientIOException} + * Retrieves the ERC20 token balance for a specific address. + * + *

Queries the token contract's balanceOf function to get the current token balance. + * The returned amount includes proper decimal formatting based on the token's decimals.

+ * + * @param address the token holder's address to query + * @param token the ERC20 token specification including contract address and decimals. + * Use {@link ERC20Token#VTHO} for VTHO or create custom token instances + * @param revision the block revision for the query. Use {@code null} for latest block, + * {@link Revision#BEST} for best block, or {@link Revision#create(long)} + * for a specific block number + * @return the token balance with proper decimal formatting + * @throws ClientIOException if there's a network error or the contract call fails + * + * @see ERC20Token#VTHO + * @see Amount#getDecimalAmount() + * @see Revision#BEST */ public static Amount getERC20Balance(Address address, ERC20Token token, Revision revision) throws ClientIOException { diff --git a/src/main/java/com/vechain/thorclient/clients/TransactionClient.java b/src/main/java/com/vechain/thorclient/clients/TransactionClient.java index 1d9b2e32..29e76c9e 100644 --- a/src/main/java/com/vechain/thorclient/clients/TransactionClient.java +++ b/src/main/java/com/vechain/thorclient/clients/TransactionClient.java @@ -26,18 +26,82 @@ import com.vechain.thorclient.utils.crypto.ECDSASign; import com.vechain.thorclient.utils.crypto.ECKeyPair; +/** + * TransactionClient provides comprehensive transaction operations for the VeChain blockchain. + * + *

Transactions are state-changing operations on the VeChain blockchain. This client provides + * transaction creation, signing, submission, and querying capabilities for both legacy and + * EIP-1559 (Galactica) transaction types.

+ * + *

Transaction Structure

+ *

VeChain transactions contain:

+ *
    + *
  • chainTag: Chain identifier (mainnet: 39, testnet: 39)
  • + *
  • blockRef: Reference block (8 bytes)
  • + *
  • expiration: Block expiration (typically 720 blocks ≈ 2 hours)
  • + *
  • clauses: Array of transaction clauses (recipient, value, data)
  • + *
  • gas: Gas limit (21000 for VET transfers, 80000+ for contracts)
  • + *
  • gasPriceCoef: Gas price coefficient (legacy transactions)
  • + *
  • maxFeePerGas: Maximum fee per gas (EIP-1559)
  • + *
  • maxPriorityFeePerGas: Priority fee (EIP-1559)
  • + *
+ * + *

Usage Examples

+ *
{@code
+ * // Send VET transfer
+ * ToClause clause = TransactionClient.buildVETToClause(
+ *     Address.fromHexString("0xRecipientAddress"),
+ *     Amount.createFromToken(AbstractToken.VET).setDecimalAmount("1.5"),
+ *     ToData.ZERO
+ * );
+ * 
+ * RawTransaction rawTx = RawTransactionFactory.getInstance().createRawTransaction(
+ *     BlockchainClient.getChainTag(),
+ *     BlockchainClient.getBlockRef(null).toByteArray(),
+ *     720,  // expiration
+ *     21000, // gas limit
+ *     (byte) 0x0, // gas coefficient
+ *     CryptoUtils.generateTxNonce(),
+ *     clause
+ * );
+ * 
+ * // Sign and send
+ * TransferResult result = TransactionClient.signThenTransfer(rawTx, keyPair);
+ * System.out.println("Transaction ID: " + result.getId());
+ * 
+ * // Check transaction status
+ * Receipt receipt = TransactionClient.getTransactionReceipt(result.getId(), null);
+ * System.out.println("Success: " + !receipt.isReverted());
+ * }
+ * + * @see Transaction + * @see RawTransaction + * @see Receipt + * @see ToClause + * @since 0.1.0 + */ public class TransactionClient extends AbstractClient { public final static int ContractGasLimit = 21000; /** - * Get transaction by transaction Id. - * - * @param txId required transaction id . - * @param isRaw is response raw transaction. - * @param revision {@link Revision} revision. - * @return Transaction {@link Transaction} - * @throws ClientIOException + * Retrieves transaction information by transaction ID. + * + *

Returns complete transaction information including clauses, gas usage, + * origin address, and execution metadata. The transaction must be included + * in a block to be retrievable.

+ * + * @param txId the transaction ID (hex string with 0x prefix). Must be a valid + * 64-character hex string representing a transaction hash + * @param isRaw whether to return raw transaction data format + * @param revision the block revision context for the query. Use {@code null} + * for latest, or specify a block revision + * @return the transaction information, or {@code null} if not found + * @throws ClientIOException if there's a network error or the request fails + * @throws ClientArgumentException if the transaction ID format is invalid + * + * @see #getTransactionReceipt(String, Revision) + * @see Transaction */ public static Transaction getTransaction(String txId, boolean isRaw, Revision revision) throws ClientIOException { if (!BlockchainUtils.isId(txId)) { diff --git a/src/main/java/com/vechain/thorclient/core/model/clients/Address.java b/src/main/java/com/vechain/thorclient/core/model/clients/Address.java index 53bbcef7..fa2b5cc0 100644 --- a/src/main/java/com/vechain/thorclient/core/model/clients/Address.java +++ b/src/main/java/com/vechain/thorclient/core/model/clients/Address.java @@ -8,7 +8,47 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** - * Address object is wrapped address string or byte array. + * Represents a VeChain blockchain address with validation and conversion utilities. + * + *

Address is a fundamental type in the VeChain ecosystem, representing 20-byte + * hexadecimal identifiers for accounts and contracts. This class provides safe + * construction, validation, and conversion methods.

+ * + *

Address Format

+ *

VeChain addresses are 20-byte (160-bit) values typically represented as:

+ *
    + *
  • 40-character hexadecimal strings (with or without 0x prefix)
  • + *
  • 20-byte arrays
  • + *
+ * + *

Special Addresses

+ *
    + *
  • {@link #NULL_ADDRESS}: Zero address (0x0000...0000)
  • + *
  • {@link #VTHO_Address}: VTHO token contract address
  • + *
+ * + *

Usage Examples

+ *
{@code
+ * // Create from hex string
+ * Address addr1 = Address.fromHexString("0x1234567890123456789012345678901234567890");
+ * Address addr2 = Address.fromHexString("1234567890123456789012345678901234567890");
+ * 
+ * // Create from bytes
+ * byte[] addressBytes = new byte[20];
+ * Address addr3 = Address.fromBytes(addressBytes);
+ * 
+ * // Convert to different formats
+ * String hex = addr1.toHexString(Prefix.ZeroLowerX); // "0x1234..."
+ * String hexNoPrefix = addr1.toHexString(null);      // "1234..."
+ * byte[] bytes = addr1.getBytes();
+ * 
+ * // Use predefined addresses
+ * Address vthoContract = Address.VTHO_Address;
+ * Address nullAddr = Address.NULL_ADDRESS;
+ * }
+ * + * @see Prefix + * @since 0.1.0 */ @JsonSerialize(using = AddressSerializer.class) public class Address { diff --git a/src/main/java/com/vechain/thorclient/core/model/clients/Amount.java b/src/main/java/com/vechain/thorclient/core/model/clients/Amount.java index 3d39b72d..7888b558 100644 --- a/src/main/java/com/vechain/thorclient/core/model/clients/Amount.java +++ b/src/main/java/com/vechain/thorclient/core/model/clients/Amount.java @@ -12,7 +12,45 @@ import com.vechain.thorclient.utils.StringUtils; /** - * Amount for {@link ToClause} to use. + * Represents token amounts with decimal precision for VeChain transactions. + * + *

Amount handles token values with proper decimal formatting, supporting both + * native VET and ERC20 tokens like VTHO. It provides conversion between decimal + * representations and wei (smallest unit) values.

+ * + *

Supported Tokens

+ *
    + *
  • VET: Native VeChain token (18 decimals)
  • + *
  • VTHO: VeChain energy token (18 decimals)
  • + *
  • Custom ERC20: Any ERC20 token with configurable decimals
  • + *
+ * + *

Usage Examples

+ *
{@code
+ * // Create VET amount
+ * Amount vetAmount = Amount.createFromToken(AbstractToken.VET);
+ * vetAmount.setDecimalAmount("10.5");
+ * System.out.println("VET: " + vetAmount.getDecimalAmount());
+ * 
+ * // Create VTHO amount
+ * Amount vthoAmount = Amount.createFromToken(ERC20Token.VTHO);
+ * vthoAmount.setDecimalAmount("1000");
+ * 
+ * // Convert to wei (BigInteger)
+ * BigInteger weiValue = vetAmount.toBigInteger();
+ * 
+ * // Use zero amount
+ * Amount zero = Amount.ZERO;
+ * 
+ * // Convenient factory methods
+ * Amount vet = Amount.VET().setDecimalAmount("5.0");
+ * Amount vtho = Amount.VTHO().setDecimalAmount("100");
+ * }
+ * + * @see AbstractToken + * @see ERC20Token + * @see ToClause + * @since 0.1.0 */ public class Amount { /** From 574d6723001763cc22e88da7ab4bde6e326a260a Mon Sep 17 00:00:00 2001 From: Andreas Frank Date: Thu, 11 Sep 2025 15:57:26 +0300 Subject: [PATCH 3/4] fix: fixed docker --- docker-compose.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yaml b/docker-compose.yaml index 3592a97f..7533a8f1 100644 --- a/docker-compose.yaml +++ b/docker-compose.yaml @@ -1,6 +1,6 @@ services: thor-solo: - image: ghcr.io/vechain/thor:darren-fix-packer-balance-check-0ffe8bccb7c6c8edd4364080bbcfba3c6e3b1964 + image: vechain/thor:latest hostname: thor-solo container_name: thor-solo user: root From 64385d32528925adf83a349825b4d5f7400319ed Mon Sep 17 00:00:00 2001 From: Andreas Frank Date: Thu, 11 Sep 2025 16:04:34 +0300 Subject: [PATCH 4/4] fix: fixed docs --- README.md | 10 ++ docs/MAIN_DOCUMENTATION.md | 130 +++----------------------- docs/MODEL_CLASSES_REFERENCE.md | 156 ++++---------------------------- 3 files changed, 41 insertions(+), 255 deletions(-) diff --git a/README.md b/README.md index 46994491..ffaf5670 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,16 @@ A SDK toolkit for JDK to call VeChainThor Restful API. +## 📚 Documentation + +For comprehensive integration guides, API references, and examples, visit our detailed documentation: + +- **[Partner Integration Guide](docs/MAIN_DOCUMENTATION.md)** - Complete guide with all SDK functions and practical examples +- **[Model Classes Reference](docs/MODEL_CLASSES_REFERENCE.md)** - Reference for all data models and types +- **[Multi-Party Payment Guide](docs/PROTOTYPE_CONTRACT_GUIDE.md)** - MPP implementation guide + +The documentation includes dynamic links to Javadoc for up-to-date type and field references. + > [!WARNING] > This repository is not actively maintained. > diff --git a/docs/MAIN_DOCUMENTATION.md b/docs/MAIN_DOCUMENTATION.md index 57b8d5d3..eaf0d91b 100644 --- a/docs/MAIN_DOCUMENTATION.md +++ b/docs/MAIN_DOCUMENTATION.md @@ -71,36 +71,13 @@ Blocks are the fundamental units of the VeChain blockchain, containing transacti ### Data Types #### Block -Represents a complete blockchain block. - -**Fields**: -- `number`: Block number (string) -- `id`: Block ID (hex string) -- `size`: Block size in bytes -- `parentID`: Parent block ID -- `timestamp`: Block timestamp (Unix) -- `gasLimit`: Block gas limit -- `gasUsed`: Gas used in block -- `totalScore`: Cumulative difficulty -- `txsRoot`: Transactions merkle root -- `stateRoot`: State merkle root -- `receiptsRoot`: Receipts merkle root -- `signer`: Block signer address -- `beneficiary`: Block reward recipient -- `isTrunk`: Whether block is on main chain -- `transactions`: Array of transaction IDs or full transactions -- `baseFeePerGas`: Base fee per gas (Galactica) +Represents a complete blockchain block. See [Block Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Block.html) for complete field reference. #### BlockRef -Block reference used for transaction construction. - -**Methods**: -- `toByteArray()`: Convert to 8-byte array for transactions +Block reference used for transaction construction. See [BlockRef Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/BlockRef.html) for methods and usage. #### Revision -Specifies which block to query. - -**Types**: +Specifies which block to query. See [Revision Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Revision.html) for available options: - `Revision.BEST`: Latest block - `Revision.create(blockNumber)`: Specific block number - `null`: Defaults to best block @@ -217,66 +194,22 @@ Transactions are state-changing operations on the VeChain blockchain. The SDK pr ### Data Types #### Transaction -Complete transaction information. - -**Fields**: -- `id`: Transaction ID (hex string) -- `chainTag`: Chain identifier -- `blockRef`: Reference block (8 bytes) -- `expiration`: Block expiration -- `clauses`: Array of transaction clauses -- `gasPriceCoef`: Gas price coefficient -- `gas`: Gas limit -- `origin`: Transaction sender -- `delegator`: Fee delegator (if applicable) -- `size`: Transaction size -- `meta`: Transaction metadata -- `type`: Transaction type (0=legacy, 2=EIP-1559) -- `maxFeePerGas`: Maximum fee per gas (EIP-1559) -- `maxPriorityFeePerGas`: Maximum priority fee (EIP-1559) +Complete transaction information. See [Transaction Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Transaction.html) for complete field reference including EIP-1559 support. #### RawTransaction -Unsigned transaction data for construction. - -**Fields**: -- `chainTag`: Chain identifier -- `blockRef`: Reference block bytes -- `expiration`: Block expiration -- `clauses`: Transaction clauses -- `gasPriceCoef`: Gas price coefficient -- `gas`: Gas limit -- `dependsOn`: Transaction dependency -- `nonce`: Random nonce -- `signature`: Transaction signature -- `maxFeePerGas`: Maximum fee (EIP-1559) -- `maxPriorityFeePerGas`: Priority fee (EIP-1559) +Unsigned transaction data for construction. See [RawTransaction Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/RawTransaction.html) for all fields and methods. #### ToClause -Transaction clause specifying recipient, value, and data. - -**Constructor**: +Transaction clause specifying recipient, value, and data. See [ToClause Javadoc](../doc/com/vechain/thorclient/core/model/clients/ToClause.html) for constructor details: ```java ToClause(Address to, Amount value, ToData data) ``` #### Receipt -Transaction execution result. - -**Fields**: -- `gasUsed`: Gas consumed -- `gasPayer`: Address that paid gas -- `paid`: Total VTHO paid -- `reward`: Block reward -- `reverted`: Whether execution failed -- `meta`: Receipt metadata -- `outputs`: Array of clause outputs -- `type`: Transaction type +Transaction execution result. See [Receipt Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Receipt.html) for complete field reference. #### TransferResult -Result of transaction submission. - -**Fields**: -- `id`: Transaction ID +Result of transaction submission. See [TransferResult Javadoc](../doc/com/vechain/thorclient/core/model/clients/TransferResult.html) for details. ### Functions @@ -474,38 +407,16 @@ Accounts represent addresses on the VeChain blockchain, containing VET/VTHO bala ### Data Types #### Account -Account state information. - -**Fields**: -- `balance`: VET balance (hex string in wei) -- `energy`: VTHO balance (hex string in wei) -- `hasCode`: Whether address contains contract code +Account state information. See [Account Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Account.html) for complete field reference. #### AccountCode -Contract bytecode at an address. - -**Fields**: -- `code`: Contract bytecode (hex string) +Contract bytecode at an address. See [AccountCode Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/AccountCode.html) for details. #### AccountCall -Request for contract view function calls. - -**Fields**: -- `clauses`: Array of call clauses -- `caller`: Caller address -- `gas`: Gas limit -- `gasPrice`: Gas price +Request for contract view function calls. See [AccountCall Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/AccountCall.html) for field specifications. #### AccountCallResult -Result of account call execution. - -**Fields**: -- `data`: Return data -- `events`: Emitted events -- `transfers`: Value transfers -- `gasUsed`: Gas consumed -- `reverted`: Execution status -- `vmError`: VM error message +Result of account call execution. See [AccountCallResult Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/AccountCallResult.html) for complete result structure. ### Functions @@ -589,25 +500,12 @@ ERC20 tokens on VeChain, including the native VTHO token. The SDK provides speci ### Data Types #### ERC20Token -Token specification. - -**Constants**: +Token specification. See [ERC20Token Javadoc](../doc/com/vechain/thorclient/core/model/clients/ERC20Token.html) for constants and field details: - `ERC20Token.VTHO`: VTHO token contract - `ERC20Token.VET`: VET compatibility token -**Fields**: -- `contractAddress`: Token contract address -- `decimals`: Token decimal places -- `symbol`: Token symbol - #### Amount -Token amount with decimal precision. - -**Methods**: -- `createFromToken(token)`: Create for specific token -- `setDecimalAmount(String)`: Set decimal amount -- `toBigInteger()`: Convert to wei -- `getDecimalAmount()`: Get decimal string +Token amount with decimal precision. See [Amount Javadoc](../doc/com/vechain/thorclient/core/model/clients/Amount.html) for methods and usage. ### Functions diff --git a/docs/MODEL_CLASSES_REFERENCE.md b/docs/MODEL_CLASSES_REFERENCE.md index 92d883e2..e3ea9ec0 100644 --- a/docs/MODEL_CLASSES_REFERENCE.md +++ b/docs/MODEL_CLASSES_REFERENCE.md @@ -3,165 +3,55 @@ ## Core Data Types ### Address -Represents a VeChain address. - -**Methods**: -- `fromHexString(String hex)`: Create from hex string -- `toHexString(Prefix prefix)`: Convert to hex string -- `getBytes()`: Get raw bytes - -**Constants**: -- `Address.VTHO_Address`: VTHO token contract address -- `Address.NULL_ADDRESS`: Zero address +Represents a VeChain address. See [Address Javadoc](../doc/com/vechain/thorclient/core/model/clients/Address.html) for complete method reference and constants. ### Amount -Represents token amounts with decimal precision. - -**Methods**: -- `createFromToken(AbstractToken token)`: Create for specific token -- `setDecimalAmount(String amount)`: Set decimal amount -- `toBigInteger()`: Convert to BigInteger (wei) -- `getDecimalAmount()`: Get decimal representation +Represents token amounts with decimal precision. See [Amount Javadoc](../doc/com/vechain/thorclient/core/model/clients/Amount.html) for all methods and usage patterns. ### Revision -Represents block revision for queries. - -**Static Methods**: -- `Revision.BEST`: Latest block -- `Revision.create(long blockNumber)`: Specific block number +Represents block revision for queries. See [Revision Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Revision.html) for static methods and usage. ## Transaction Models ### RawTransaction -Unsigned transaction data. - -**Fields**: -- `chainTag`: Chain identifier -- `blockRef`: Reference block -- `expiration`: Block expiration -- `clauses`: Transaction clauses -- `gasPriceCoef`: Gas price coefficient -- `gas`: Gas limit -- `dependsOn`: Transaction dependency -- `nonce`: Transaction nonce -- `signature`: Transaction signature +Unsigned transaction data. See [RawTransaction Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/RawTransaction.html) for complete field reference. ### ToClause -Transaction clause specifying recipient, value, and data. - -**Constructor**: -```java -ToClause(Address to, Amount value, ToData data) -``` +Transaction clause specifying recipient, value, and data. See [ToClause Javadoc](../doc/com/vechain/thorclient/core/model/clients/ToClause.html) for constructor details. ### ToData -Transaction data payload. - -**Methods**: -- `ToData.ZERO`: Empty data -- `setData(String hexData)`: Set hex data +Transaction data payload. See [ToData Javadoc](../doc/com/vechain/thorclient/core/model/clients/ToData.html) for methods and constants. ### TransferResult -Result of transaction submission. - -**Fields**: -- `id`: Transaction ID -- `success`: Success status +Result of transaction submission. See [TransferResult Javadoc](../doc/com/vechain/thorclient/core/model/clients/TransferResult.html) for field details. ### Transaction -Complete transaction information. - -**Fields**: -- `id`: Transaction ID -- `chainTag`: Chain tag -- `blockRef`: Block reference -- `expiration`: Expiration -- `clauses`: Transaction clauses -- `gasPriceCoef`: Gas price coefficient -- `gas`: Gas limit -- `origin`: Transaction origin -- `delegator`: Delegator address (if applicable) -- `size`: Transaction size -- `meta`: Transaction metadata +Complete transaction information. See [Transaction Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Transaction.html) for complete field reference including EIP-1559 support. ### Receipt -Transaction execution receipt. - -**Fields**: -- `gasUsed`: Gas consumed -- `gasPayer`: Address that paid gas -- `paid`: Total payment -- `reward`: Block reward -- `reverted`: Execution status -- `meta`: Receipt metadata -- `outputs`: Transaction outputs +Transaction execution receipt. See [Receipt Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Receipt.html) for complete field reference. ## Block Models ### Block -Blockchain block information. - -**Fields**: -- `number`: Block number -- `id`: Block ID -- `size`: Block size -- `parentID`: Parent block ID -- `timestamp`: Block timestamp -- `gasLimit`: Gas limit -- `gasUsed`: Gas used -- `totalScore`: Total score -- `txsRoot`: Transactions root -- `stateRoot`: State root -- `receiptsRoot`: Receipts root -- `signer`: Block signer -- `beneficiary`: Beneficiary address -- `isTrunk`: Trunk status -- `transactions`: Transaction list - -**Methods**: -- `blockRef()`: Get BlockRef for transactions +Blockchain block information. See [Block Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Block.html) for complete field reference and methods. ### BlockRef -Block reference for transaction construction. - -**Methods**: -- `toByteArray()`: Convert to byte array +Block reference for transaction construction. See [BlockRef Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/BlockRef.html) for methods. ## Account Models ### Account -Account state information. - -**Fields**: -- `balance`: VET balance (hex string) -- `energy`: VTHO balance (hex string) -- `hasCode`: Contract indicator +Account state information. See [Account Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/Account.html) for field details. ### AccountCode -Contract bytecode information. - -**Fields**: -- `code`: Contract bytecode (hex string) +Contract bytecode information. See [AccountCode Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/AccountCode.html) for field details. ### AccountCall -Account call request for contract interaction. - -**Fields**: -- `clauses`: Call clauses -- `caller`: Caller address -- `gas`: Gas limit -- `gasPrice`: Gas price +Account call request for contract interaction. See [AccountCall Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/AccountCall.html) for field specifications. ### AccountCallResult -Result of account call. - -**Fields**: -- `data`: Return data -- `events`: Emitted events -- `transfers`: Value transfers -- `gasUsed`: Gas consumed -- `reverted`: Execution status -- `vmError`: VM error message +Result of account call. See [AccountCallResult Javadoc](../doc/com/vechain/thorclient/core/model/blockchain/AccountCallResult.html) for complete result structure. ## Contract Models @@ -364,22 +254,10 @@ Result ordering specification. ## Token Models ### ERC20Token -ERC20 token specification. - -**Constants**: -- `ERC20Token.VTHO`: VTHO token -- `ERC20Token.VET`: VET token (for compatibility) - -**Fields**: -- `contractAddress`: Token contract address -- `decimals`: Token decimals -- `symbol`: Token symbol +ERC20 token specification. See [ERC20Token Javadoc](../doc/com/vechain/thorclient/core/model/clients/ERC20Token.html) for constants and field details. ### AbstractToken -Base token interface. - -**Constants**: -- `AbstractToken.VET`: Native VET token +Base token interface. See [AbstractToken Javadoc](../doc/com/vechain/thorclient/core/model/clients/AbstractToken.html) for constants and methods. ## Error Models