diff --git a/docs/Developer Tools/Chain Sdk/_category_.json b/docs/Developer Tools/Chain Sdk/_category_.json new file mode 100644 index 00000000..611ac3cd --- /dev/null +++ b/docs/Developer Tools/Chain Sdk/_category_.json @@ -0,0 +1,4 @@ +{ + "position": 2, + "label": "Chain SDK" +} diff --git a/docs/Developer Tools/Chain Sdk/csharp-sdk.md b/docs/Developer Tools/Chain Sdk/csharp-sdk.md new file mode 100644 index 00000000..ef06ba0f --- /dev/null +++ b/docs/Developer Tools/Chain Sdk/csharp-sdk.md @@ -0,0 +1,523 @@ +--- +sidebar_position: 2 +title: C# SDK +description: C# SDK +--- + +# aelf-sdk.cs - aelf C# API + +`aelf-sdk.cs` is a C# library that facilitates communication with an AElf node over HTTP. Below is a comprehensive guide on how to install and use the `aelf-sdk.cs` package, along with some example usages. + + +## Introduction + +`aelf-sdk.cs` is a collection of libraries designed for interaction with both local and remote AElf nodes via HTTP connections. This documentation provides instructions on how to install and run `aelf-sdk.cs`, and includes API reference documentation with examples. [aelf-sdk.cs](https://github.com/AElfProject/aelf-sdk.cs) + + +## Adding aelf-sdk.cs package + +To use `aelf-sdk.cs`, you need to add the AElf.Client package to your project. This can be done using various methods: + + +### Using Package Manager + +Open the Package Manager Console in Visual Studio and run: + +```sh +PM> Install-Package AElf.Client +``` + + +### Using .NET CLI + +Run the following command in your terminal: + +```sh +dotnet add package AElf.Client +``` + + +### Using PackageReference + +Add the following line to your `.csproj` file: + +```sh + +``` + +Replace `X.X.X` with the desired version of the `AElf.Client` package. + + +## Examples + + +### 1. Create Instance + +Create a new instance of AElfClient and set the URL of an AElf chain node. + +```csharp +using AElf.Client.Service; + +// Create a new instance of AElfClient +AElfClient client = new AElfClient("http://127.0.0.1:1235"); +``` + + +### 2. Test Connection + +Check that the AElf chain node is connectable. + +```csharp +var isConnected = await client.IsConnectedAsync(); +Console.WriteLine($"Connected: {isConnected}"); +``` + + +### 3. Initiate a Transfer Transaction + + +#### a. Get Token Contract Address + +```csharp +using AElf.Client.Helpers; +using AElf.Types; +using Google.Protobuf; +using AElf.Client.Dto; +using AElf.Contracts.MultiToken.Messages; + +// Get token contract address. +var tokenContractAddress = await client.GetContractAddressByNameAsync(HashHelper.ComputeFrom("AElf.ContractNames.Token")); +``` + +#### b. Prepare Transfer Parameters + +```csharp +var methodName = "Transfer"; +var param = new TransferInput +{ + To = new Address {Value = Address.FromBase58("7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz").Value}, + Symbol = "ELF", + Amount = 1000000000, // 10 ELF with 8 decimal places + Memo = "transfer in demo" +}; +var ownerAddress = client.GetAddressFromPrivateKey(PrivateKey); +``` + +#### c. Generate and Sign Transaction + +```csharp +// Generate a transfer transaction. +var transaction = await client.GenerateTransaction(ownerAddress, tokenContractAddress.ToBase58(), methodName, param); +var txWithSign = client.SignTransaction(PrivateKey, transaction); +``` + +#### d. Send Transaction to AElf Chain Node + +```csharp +// Send the transfer transaction to AElf chain node. +var result = await client.SendTransactionAsync(new SendTransactionInput +{ + RawTransaction = txWithSign.ToByteArray().ToHex() +}); + +// Wait for the transaction to be mined +await Task.Delay(4000); + +// After the transaction is mined, query the execution results. +var transactionResult = await client.GetTransactionResultAsync(result.TransactionId); +Console.WriteLine($"Transaction Status: {transactionResult.Status}"); +``` + + +### 4. Query Account Balance + +#### a. Prepare Get Balance Parameters + +```csharp +var paramGetBalance = new GetBalanceInput +{ + Symbol = "ELF", + Owner = new Address {Value = Address.FromBase58(ownerAddress).Value} +}; +``` + +#### b. Generate and Sign Get Balance Transaction + +```csharp +var transactionGetBalance = await client.GenerateTransaction(ownerAddress, tokenContractAddress.ToBase58(), "GetBalance", paramGetBalance); +var txWithSignGetBalance = client.SignTransaction(PrivateKey, transactionGetBalance); +``` + +#### c. Execute Get Balance Transaction + +```csharp +var transactionGetBalanceResult = await client.ExecuteTransactionAsync(new ExecuteTransactionDto +{ + RawTransaction = txWithSignGetBalance.ToByteArray().ToHex() +}); + +var balance = GetBalanceOutput.Parser.ParseFrom(ByteArrayHelper.HexstringToByteArray(transactionGetBalanceResult)); +Console.WriteLine($"Account Balance: {balance.Balance}"); +``` + + +## Web API + +Here are the examples and code snippets for interacting with the AElf Web API using the `AElfClient` instance. + +### 1. Create Instance + +Create a new instance of AElfClient and set the URL of an AElf chain node. + +```csharp +using AElf.Client.Service; + +// Create a new instance of AElfClient, change the URL if needed +AElfClient client = new AElfClient("http://127.0.0.1:1235"); +``` + + +### 2. Get Chain Status + +Get the current status of the blockchain. + +```csharp +var chainStatus = await client.GetChainStatusAsync(); +Console.WriteLine($"Chain ID: {chainStatus.ChainId}"); +Console.WriteLine($"Best Chain Height: {chainStatus.BestChainHeight}"); +``` + + +### 3. Get Contract File Descriptor Set + +Get the protobuf definitions related to a contract. + +```csharp +string contractAddress = "YOUR_CONTRACT_ADDRESS"; +var fileDescriptorSet = await client.GetContractFileDescriptorSetAsync(contractAddress); +Console.WriteLine($"File Descriptor Set: {fileDescriptorSet.Length} bytes"); +``` + + +### 4. Get Block Height + +Get the current best height of the chain. + +```csharp +var blockHeight = await client.GetBlockHeightAsync(); +Console.WriteLine($"Block Height: {blockHeight}"); +``` + + +### 5. Get Block Information by Block Hash + +Get block information by block hash. + +```csharp +string blockHash = "YOUR_BLOCK_HASH"; +var block = await client.GetBlockByHashAsync(blockHash); +Console.WriteLine($"Block Hash: {block.BlockHash}"); +Console.WriteLine($"Block Height: {block.Header.Height}"); +``` + + +### 6. Get Block Information by Block Height + +Get block information by block height. + +```csharp +long height = 100; +var blockByHeight = await client.GetBlockByHeightAsync(height); +Console.WriteLine($"Block Hash: {blockByHeight.BlockHash}"); +Console.WriteLine($"Block Height: {blockByHeight.Header.Height}"); +``` + + +### 7. Get Transaction Result + +Get the result of a transaction. + +```csharp +string transactionId = "YOUR_TRANSACTION_ID"; +var transactionResult = await client.GetTransactionResultAsync(transactionId); +Console.WriteLine($"Transaction Status: {transactionResult.Status}"); +Console.WriteLine($"Block Number: {transactionResult.BlockNumber}"); +``` + + +### 8. Get Multiple Transaction Results in a Block + +Get multiple transaction results in a block. + +```csharp +string blockHashForTransactions = "YOUR_BLOCK_HASH"; +var transactionResults = await client.GetTransactionResultsAsync(blockHashForTransactions, 0, 10); +foreach (var result in transactionResults) +{ + Console.WriteLine($"Transaction ID: {result.TransactionId}, Status: {result.Status}"); +} +``` + +### 9. Get Transaction Pool Status + +Get the transaction pool status. + +```csharp +var transactionPoolStatus = await client.GetTransactionPoolStatusAsync(); +Console.WriteLine($"Queued Transactions: {transactionPoolStatus.Queued}"); +Console.WriteLine($"Validated Transactions: {transactionPoolStatus.Validated}"); +``` + +### 10. Send Transaction + +Broadcast a transaction. + +```csharp +var sendTransactionInput = new SendTransactionInput +{ + RawTransaction = "YOUR_RAW_TRANSACTION" +}; +var sendTransactionOutput = await client.SendTransactionAsync(sendTransactionInput); +Console.WriteLine($"Transaction ID: {sendTransactionOutput.TransactionId}"); +``` + +### 11. Send Raw Transaction + +Broadcast a raw transaction. + +```csharp +var sendRawTransactionInput = new SendRawTransactionInput +{ + Transaction = "YOUR_RAW_TRANSACTION", + Signature = "YOUR_SIGNATURE", + ReturnTransaction = true +}; +var sendRawTransactionOutput = await client.SendRawTransactionAsync(sendRawTransactionInput); +Console.WriteLine($"Transaction ID: {sendRawTransactionOutput.TransactionId}"); +``` + +### 12. Send Multiple Transactions + +Broadcast multiple transactions. + +```csharp +var sendTransactionsInput = new SendTransactionsInput +{ + RawTransactions = new[] { "RAW_TRANSACTION_1", "RAW_TRANSACTION_2" } +}; +var transactionIds = await client.SendTransactionsAsync(sendTransactionsInput); +foreach (var id in transactionIds) +{ + Console.WriteLine($"Transaction ID: {id}"); +} +``` + +### 13. Create Raw Transaction + +Creates an unsigned serialized transaction. + +```csharp +var createRawTransactionInput = new CreateRawTransactionInput +{ + From = "FROM_ADDRESS", + To = "TO_ADDRESS", + RefBlockNumber = 100, + RefBlockHash = "BLOCK_HASH", + MethodName = "METHOD_NAME", + Params = "PARAMETERS" +}; +var createRawTransactionOutput = await client.CreateRawTransactionAsync(createRawTransactionInput); +Console.WriteLine($"Raw Transaction: {createRawTransactionOutput.RawTransaction}"); +``` + +### 14. Execute Transaction + +Call a read-only method on a contract. + +```csharp +var executeTransactionDto = new ExecuteTransactionDto +{ + RawTransaction = "YOUR_RAW_TRANSACTION" +}; +var executionResult = await client.ExecuteTransactionAsync(executeTransactionDto); +Console.WriteLine($"Execution Result: {executionResult}"); +``` + +### 15. Execute Raw Transaction + +Call a read-only method on a contract with a raw transaction. + +```csharp +var executeRawTransactionDto = new ExecuteRawTransactionDto +{ + RawTransaction = "YOUR_RAW_TRANSACTION", + Signature = "YOUR_SIGNATURE" +}; +var executeRawResult = await client.ExecuteRawTransactionAsync(executeRawTransactionDto); +Console.WriteLine($"Execution Result: {executeRawResult}"); +``` + + +### 16. Get Peers + +Get peer info about the connected network nodes. + +```csharp +var peers = await client.GetPeersAsync(false); +foreach (var peer in peers) +{ + Console.WriteLine($"Peer IP: {peer.IpAddress}, Connection Status: {peer.ConnectionStatus}"); +} +``` + + +### 17. Add Peer + +Attempts to add a node to the connected network nodes. + + +```csharp +var isPeerAdded = await client.AddPeerAsync("127.0.0.1:7001"); +Console.WriteLine($"Peer Added: {isPeerAdded}"); +``` + + +### 18. Remove Peer + +Attempts to remove a node from the connected network nodes. + +```csharp +var isPeerRemoved = await client.RemovePeerAsync("127.0.0.1:7001"); +Console.WriteLine($"Peer Removed: {isPeerRemoved}"); +``` + + +### 19. Calculate Transaction Fee + +```csharp +var calculateTransactionFeeInput = new CalculateTransactionFeeInput +{ + RawTransaction = "YOUR_RAW_TRANSACTION" +}; +var transactionFeeResult = await client.CalculateTransactionFeeAsync(calculateTransactionFeeInput); +Console.WriteLine($"Transaction Fee: {transactionFeeResult.TransactionFee}"); +``` + + +### 20. Get Network Information + +```csharp +var networkInfo = await client.GetNetworkInfoAsync(); +Console.WriteLine($"Network Version: {networkInfo.Version}"); +Console.WriteLine($"Connections: {networkInfo.Connections}"); +``` + +These examples demonstrate how to use the AElf Web API in C# using the `AElfClient` class to interact with the AElf blockchain, including checking chain status, handling transactions, and managing network peers. + + +## aelf Client + +### 1. IsConnected + +Verify whether this SDK successfully connects to the chain. + +```csharp +bool isConnected = await client.IsConnectedAsync(); +Console.WriteLine($"Is Connected: {isConnected}"); +``` + +### 2. GetGenesisContractAddress + +Get the address of the genesis contract. + + +```csharp +string genesisContractAddress = await client.GetGenesisContractAddressAsync(); +Console.WriteLine($"Genesis Contract Address: {genesisContractAddress}"); +``` + +### 3. GetContractAddressByName + +Get the address of a contract by the given contract name hash. + + +```csharp +var contractNameHash = HashHelper.ComputeFrom("AElf.ContractNames.Token"); +string contractAddress = await client.GetContractAddressByNameAsync(contractNameHash); +Console.WriteLine($"Contract Address: {contractAddress}"); +``` + +### 4. GenerateTransaction + +Build a transaction from the input parameters. + + +```csharp +string from = "FROM_ADDRESS"; +string to = "TO_ADDRESS"; +string methodName = "Transfer"; +var input = new TransferInput +{ + To = new Address { Value = Address.FromBase58("TO_ADDRESS").Value }, + Symbol = "ELF", + Amount = 1000000000, + Memo = "Transfer example" +}; + +Transaction transaction = await client.GenerateTransactionAsync(from, to, methodName, input); +Console.WriteLine($"Transaction: {transaction}"); +``` + +### 5. GetFormattedAddress + +Convert the `Address` to the displayed string format: symbol_base58-string_base58-string_chain-id. + +```csharp +Address address = new Address { Value = Address.FromBase58("ADDRESS").Value }; +string formattedAddress = await client.GetFormattedAddressAsync(address); +Console.WriteLine($"Formatted Address: {formattedAddress}"); +``` + +### 6. SignTransaction + +```csharp +string privateKeyHex = "YOUR_PRIVATE_KEY_HEX"; +Transaction signedTransaction = client.SignTransaction(privateKeyHex, transaction); +Console.WriteLine($"Signed Transaction: {signedTransaction}"); +``` + +### 7. GetAddressFromPubKey + +Get the account address through the public key. + +```csharp +string pubKey = "YOUR_PUBLIC_KEY"; +string addressFromPubKey = client.GetAddressFromPubKey(pubKey); +Console.WriteLine($"Address from PubKey: {addressFromPubKey}"); +``` + +### 8. GetAddressFromPrivateKey + +Get the account address through the private key. + +```csharp +string privateKeyHex = "YOUR_PRIVATE_KEY_HEX"; +string addressFromPrivateKey = client.GetAddressFromPrivateKey(privateKeyHex); +Console.WriteLine($"Address from Private Key: {addressFromPrivateKey}"); +``` + +### 9. GenerateKeyPairInfo + +Generate a new account key pair. + + +```csharp +var keyPairInfo = client.GenerateKeyPairInfo(); +Console.WriteLine($"Private Key: {keyPairInfo.PrivateKey}"); +Console.WriteLine($"Public Key: {keyPairInfo.PublicKey}"); +Console.WriteLine($"Address: {keyPairInfo.Address}"); +``` + +## Supports + +.NET Standard 2.0 \ No newline at end of file diff --git a/docs/Developer Tools/Chain Sdk/go-sdk.md b/docs/Developer Tools/Chain Sdk/go-sdk.md new file mode 100644 index 00000000..c87e132e --- /dev/null +++ b/docs/Developer Tools/Chain Sdk/go-sdk.md @@ -0,0 +1,709 @@ +--- +sidebar_position: 3 +title: Go SDK +description: Go SDK +--- + +# aelf-sdk.go - aelf Go API + +## Introduction +---------- + +This document provides information on how to use the AElf Go SDK (aelf-sdk.go) to interact with an AElf node. The SDK allows you to communicate with a local or remote AElf node using HTTP. Here you will find instructions for setting up the SDK, examples of how to use it, and a brief description of its main functions. + +For additional information, please visit the repository: [aelf-sdk.go](https://github.com/AElfProject/aelf-sdk.go) + +## Installation +---------- + +To install the `aelf-sdk.go` package, run the following command: + +```sh +go get -u github.com/AElfProject/aelf-sdk.go +``` + +## Examples +---------- + + +### Create instance + +Create a new instance of `AElfClient` and set the URL of an AElf chain node: + +```go +import ( + "github.com/AElfProject/aelf-sdk.go/client" + "github.com/AElfProject/aelf-sdk.go/util" + "github.com/AElfProject/aelf-sdk.go/pb" + "github.com/golang/protobuf/proto" + "encoding/hex" + "fmt" + "time" +) + +var aelf = client.AElfClient{ + Host: "http://127.0.0.1:8000", + Version: "1.0", + PrivateKey: "cd86ab6347d8e52bbbe8532141fc59ce596268143a308d1d40fedf385528b458", +} +``` + +### Initiating a Transfer Transaction + +Here is an example of how to initiate a transfer transaction using the aelf Go SDK: + +#### 1. Get the Token Contract Address: + +```go +tokenContractAddress, _ := aelf.GetContractAddressByName("AElf.ContractNames.Token") +fromAddress := aelf.GetAddressFromPrivateKey(aelf.PrivateKey) +methodName := "Transfer" +toAddress, _ := util.Base58StringToAddress("7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz") +``` + +#### 2. Set Transaction Parameters: + +```go +params := &pb.TransferInput{ + To: toAddress, + Symbol: "ELF", + Amount: 1000000000, + Memo: "transfer in demo", +} +paramsByte, _ := proto.Marshal(params) +``` + +#### 3. Generate and Sign the Transaction: + +```go +transaction, _ := aelf.CreateTransaction(fromAddress, tokenContractAddress, methodName, paramsByte) +signature, _ := aelf.SignTransaction(aelf.PrivateKey, transaction) +transaction.Signature = signature +``` + +#### 4. Send the Transaction to the AElf Chain Node: + +```go +transactionBytes, _ := proto.Marshal(transaction) +sendResult, _ := aelf.SendTransaction(hex.EncodeToString(transactionBytes)) + +time.Sleep(time.Duration(4) * time.Second) +transactionResult, _ := aelf.GetTransactionResult(sendResult.TransactionID) +fmt.Println(transactionResult) +``` + +#### 5. Query Account Balance: + +```go +ownerAddress, _ := util.Base58StringToAddress(fromAddress) +getBalanceInput := &pb.GetBalanceInput{ + Symbol: "ELF", + Owner: ownerAddress, +} +getBalanceInputByte, _ := proto.Marshal(getBalanceInput) + +getBalanceTransaction, _ := aelf.CreateTransaction(fromAddress, tokenContractAddress, "GetBalance", getBalanceInputByte) +getBalanceTransaction.Params = getBalanceInputByte +getBalanceSignature, _ := aelf.SignTransaction(aelf.PrivateKey, getBalanceTransaction) +getBalanceTransaction.Signature = getBalanceSignature + +getBalanceTransactionBytes, _ := proto.Marshal(getBalanceTransaction) +getBalanceResult, _ := aelf.ExecuteTransaction(hex.EncodeToString(getBalanceTransactionBytes)) +balance := &pb.GetBalanceOutput{} +getBalanceResultBytes, _ := hex.DecodeString(getBalanceResult) +proto.Unmarshal(getBalanceResultBytes, balance) +fmt.Println(balance) +``` + + + +## Web API +---------- + +You can see how the Web API of the node works at `{chainAddress}/swagger/index.html`. For example, on a local address: `http://127.0.0.1:1235/swagger/index.html`. + +The usage of these methods is based on the `AElfClient` instance. If you don’t have one, please create it: + +```go +import ( + "github.com/AElfProject/aelf-sdk.go/client" +) + +var aelf = client.AElfClient{ + Host: "http://127.0.0.1:8000", + Version: "1.0", + PrivateKey: "680afd630d82ae5c97942c4141d60b8a9fedfa5b2864fca84072c17ee1f72d9d", +} +``` + + +### GetChainStatus + +- **Web API path**: `/api/blockChain/chainStatus` + +- **Parameters** : None + +- **Returns**: `ChainStatusDto` + - ChainId - string + - Branches - map[string]interface{} + - NotLinkedBlocks - map[string]interface{} + - LongestChainHeight - int64 + - LongestChainHash - string + - GenesisBlockHash - string + - GenesisContractAddress - string + - LastIrreversibleBlockHash - string + - LastIrreversibleBlockHeight - int64 + - BestChainHash - string + - BestChainHeight - int64 + + +#### Example: + +```go +chainStatus, err := aelf.GetChainStatus() +``` + +### GetContractFileDescriptorSet + +Get the protobuf definitions related to a contract. + +- **Web API path**: `/api/blockChain/contractFileDescriptorSet` + +- **Parameters** : + - contractAddress - string + +- **Returns**: `[]byte` + + +#### Example: + +```go +contractFile, err := aelf.GetContractFileDescriptorSet("pykr77ft9UUKJZLVq15wCH8PinBSjVRQ12sD1Ayq92mKFsJ1i") +``` + +### GetBlockHeight + +Get the current best height of the chain. + +- **Web API path**: `/api/blockChain/blockHeight` + +- **Parameters** : None + +- **Returns**: `float64` + + +#### Example: + +```go +height, err := aelf.GetBlockHeight() +``` + +### GetBlock + +Get block information by block hash. + + +- **Web API path**: `/api/blockChain/block` + +- **Parameters** : + - blockHash - string + - includeTransactions - bool + +- **Returns**: `BlockDto` + + - BlockHash - string + - Header - BlockHeaderDto + - PreviousBlockHash - string + - MerkleTreeRootOfTransactions - string + - MerkleTreeRootOfWorldState - string + - Extra - string + - Height - int64 + - Time - string + - ChainId - string + - Bloom - string + - SignerPubkey - string + - Body - BlockBodyDto + - TransactionsCount - int + - Transactions - []string + + +#### Example: + +```go +block, err := aelf.GetBlockByHash(blockHash, true) +``` + + +### GetBlockByHeight + +- **Web API path**: `/api/blockChain/blockByHeight` + +- **Parameters** : + - blockHeight - int64 + - includeTransactions - bool + +- **Returns**: `BlockDto` + + - BlockHash - string + - Header - BlockHeaderDto + - PreviousBlockHash - string + - MerkleTreeRootOfTransactions - string + - MerkleTreeRootOfWorldState - string + - Extra - string + - Height - int64 + - Time - string + - ChainId - string + - Bloom - string + - SignerPubkey - string + - Body - BlockBodyDto + - TransactionsCount - int + - Transactions - []string + + +#### Example: + +```go +block, err := aelf.GetBlockByHeight(100, true) +``` + +### GetTransactionResult + +- **Web API path**: `/api/blockChain/transactionResult` + +- **Parameters** : + - transactionId - string + +- **Returns**: `TransactionResultDto` + + - TransactionId - string + - Status - string + - Logs - []LogEventDto + - Address - string + - Name - string + - Indexed - []string + - NonIndexed - string + - Bloom - string + - BlockNumber - int64 + - BlockHash - string + - Transaction - TransactionDto + - From - string + - To - string + - RefBlockNumber - int64 + - RefBlockPrefix - string + - MethodName - string + - Params - string + - Signature - string + - ReturnValue - string + - Error - string + + +#### Example: + +```go +transactionResult, err := aelf.GetTransactionResult(transactionID) +``` + + +### GetTransactionResults + +Get multiple transaction results in a block. + +- **Web API path**: `/api/blockChain/transactionResults` + +- **Parameters** : + - blockHash - string + - offset - int + - limit - int + +- **Returns**: `[]TransactionResultDto` + - the transaction result object + + +#### Example: + +```go +transactionResults, err := aelf.GetTransactionResults(blockHash, 0, 10) +``` + +### GetTransactionPoolStatus + +- **Web API path**: `/api/blockChain/transactionPoolStatus` + +- **Parameters** : None +- **Returns**: `TransactionPoolStatusOutput` + + - Queued - int + - Validated - int + + +#### Example: + +```go +poolStatus, err := aelf.GetTransactionPoolStatus(); +``` + +### SendTransaction + +- **Web API path**: `/api/blockChain/sendTransaction` (POST) + +- **Parameters** : + - SendRawTransactionInput - struct containing `Transaction` as string, `Signature` as string, and `ReturnTransaction` as bool + +- **Returns**: `SendRawTransactionOutput` + + - TransactionId - string + - Transaction - TransactionDto + + +#### Example: + +```go +sendRawResult, err := aelf.SendRawTransaction(input) +``` + + +### SendTransactions + +- **Web API path**: `/api/blockChain/sendTransactions` (POST) + +- **Parameters** : + - rawTransactions - string + +- **Returns**: `[]interface{}` + + +#### Example: + +```go +results, err := aelf.SendTransactions(transactions) +``` + + +### CreateRawTransaction + +Creates an unsigned serialized transaction. + + +- **Web API path**: `/api/blockChain/rawTransaction` (POST) + +- **Parameters** : + - CreateRawTransactionInput - struct containing `From`, `To`, `RefBlockNumber`, `RefBlockHash`, `MethodName`, `Params` + +- **Returns**: `CreateRawTransactionOutput` + + +#### Example: + +```go +result, err := aelf.CreateRawTransaction(input) +``` + + +### ExecuteTransaction + +Call a read-only method on a contract. + + +- **Web API path**: `/api/blockChain/executeTransaction` (POST) + +- **Parameters** : + - rawTransaction - string + +- **Returns**: `string` + + +#### Example: + +```go +executeresult, err := aelf.ExecuteTransaction(rawTransaction) +``` + + +### ExecuteRawTransaction + +Call a read-only method on a contract. + + +- **Web API path**: `/api/blockChain/executeRawTransaction` (POST) + +- **Parameters** : + - ExecuteRawTransactionDto - struct containing `RawTransaction` as string, `Signature` as string + +- **Returns**: `string` + + +#### Example: + +```go +executeRawresult, err := aelf.ExecuteRawTransaction(executeRawinput) +``` + + +### GetPeers + +Get peer info about the connected network nodes. + + +- **Web API path**: `/api/net/peers` + +- **Parameters** : + - withMetrics - bool + +- **Returns**: `[]PeerDto` + + - IpAddress - string + - ProtocolVersion - int + - ConnectionTime - int64 + - ConnectionStatus - string + - Inbound - bool + - BufferedTransactionsCount - int + - BufferedBlocksCount - int + - BufferedAnnouncementsCount - int + - NodeVersion - string + - RequestMetrics - []RequestMetric + - RoundTripTime - int64 + - MethodName - string + - Info - string + - RequestTime - string + + + +#### Example: + +```go +peers, err := aelf.GetPeers(false) +``` + + +### AddPeer + +Attempts to add a node to the connected network nodes. + + +- **Web API path**: `/api/net/peer` (POST) + +- **Parameters** : + - ipAddress - string + +- **Returns**: `bool` + +#### Example: + +```go +addResult, err := aelf.AddPeer("127.0.0.1:7001") +``` + + +### RemovePeer + +Attempts to remove a node from the connected network nodes. + + +- **Web API path**: `/api/net/peer` (DELETE) + +- **Parameters** : + - ipAddress - string + +- **Returns**: `bool` + +#### Example: + +```go +removeResult, err := aelf.RemovePeer("127.0.0.1:7001") +``` + + +### CalculateTransactionFee + +Estimate transaction fee. + + +- **Web API path**: `/api/blockChain/calculateTransactionFee` (POST) + +- **Parameters** : + - CalculateTransactionFeeInput - struct containing `RawTransaction` as string + +- **Returns**: `TransactionFeeResultOutput` + - Success - bool + - TransactionFee - map[string]interface{} + - ResourceFee - map[string]interface{} + +#### Example: + +```go +calculateTransactionFee, err := aelf.CalculateTransactionFee(transactionFeeInput) +``` + + +### GetNetworkInfo + +Get the network information of the node. + + +- **Web API path**: `/api/net/networkInfo` + +- **Parameters** : Empty + +- **Returns**: `NetworkInfoOutput` + - Version - string + - ProtocolVersion - int + - Connections - int + +#### Example: + +```go +networkInfo, err := aelf.GetNetworkInfo() +``` + + + +## aelf Client + +### IsConnected + +Check if the SDK is successfully connected to the blockchain. + +- **Parameters**: None + +- **Returns** : + - `bool`: Connection status + +#### Example: + +```go +isConnected := aelf.IsConnected() +``` + + +### GetGenesisContractAddress + +- **Parameters**: None + +- **Returns** : + - `string`: Genesis contract address + +#### Example: + +```go +contractAddress, err := aelf.GetGenesisContractAddress() +``` + + +### GetContractAddressByName + +Get the address of a contract by its name hash. + +- **Parameters**: + - `contractNameHash` (string): Hash of the contract name + +- **Returns** : + - `string`: Contract address + +#### Example: + +```go +contractAddress, err := aelf.GetContractAddressByName("AElf.ContractNames.Token") +``` + + +### CreateTransaction + +Build a transaction with the provided parameters. + +- **Parameters**: + - `from` (string): Sender's address + - `to` (string): Recipient's address + - `methodName` (string): Method name + - `params` ([]byte): Method parameters + +- **Returns** : + - `Transaction`: Built transaction + +#### Example: + +```go +transaction, err := aelf.CreateTransaction(fromAddress, toAddress, methodName, param) +``` + + +### GetFormattedAddress + +Convert an address to a displayable string format: symbol_base58-string_base58-string-chain-id. + +- **Parameters**: + - `address` (string): Address to format + +- **Returns** : + - `string`: Formatted address + +#### Example: + +```go +formattedAddress, err := aelf.GetFormattedAddress(address) +``` + +### SignTransaction + +Sign a transaction using a private key. + +- **Parameters**: + - `privateKey` (string): Address to format + - `transaction` (string): Address to format + +- **Returns** : + - `[]byte`: Transaction signature + +#### Example: + +```go +signature, err := aelf.SignTransaction(privateKey, transaction) +``` + + +### GetAddressFromPubKey + +- **Parameters**: + - `pubKey` (string): Public key + +- **Returns** : + - `string`: Account address + +#### Example: + +```go +address := aelf.GetAddressFromPubKey(pubKey) +``` + + +### GetAddressFromPrivateKey + +- **Parameters**: + - `privateKey` (string): Private key + +- **Returns** : + - `string`: Account address + +#### Example: + +```go +address := aelf.GetAddressFromPrivateKey(privateKey) +``` + + +### GenerateKeyPairInfo + +- **Parameters**: None + +- **Returns** : + - `KeyPairInfo`: Contains PrivateKey, PublicKey, and Address + +#### Example: + +```go +keyPair := aelf.GenerateKeyPairInfo() +``` + + +## Supported Go Version + +- Go 1.13 diff --git a/docs/Developer Tools/Chain Sdk/java-sdk.md b/docs/Developer Tools/Chain Sdk/java-sdk.md new file mode 100644 index 00000000..a68d1587 --- /dev/null +++ b/docs/Developer Tools/Chain Sdk/java-sdk.md @@ -0,0 +1,792 @@ +--- +sidebar_position: 4 +title: JAVA SDK +description: JAVA SDK +--- + +# aelf-sdk.java - aelf Java API + +## Introduction + +`aelf-sdk.java` is a set of libraries that allow interaction with a local or remote AElf node using an HTTP connection. This documentation guides you through installing and running `aelf-sdk.java`, along with providing API reference documentation and examples. + +For more information, you can check out the [repository](https://github.com/AElfProject/aelf-sdk.java). + +## Adding aelf-sdk.java Package + +To add the `aelf-sdk.java` package to your project, use the following Maven dependency: + +```xml + + + io.aelf + aelf-sdk + 0.X.X + +``` + +## Examples + +### Create Instance + +Create a new instance of `AElfClient`, and set the URL of an AElf chain node. + +```java +import AElf.Client.Service; + +// Create a new instance of AElfClient, change the URL if needed +AElfClient client = new AElfClient("http://127.0.0.1:1235"); +``` + +### Test Connection + +Check if the AElf chain node is connectable. + +```java +boolean isConnected = client.isConnected(); +``` + +### Initiate a Transfer Transaction + +Initiate a transfer transaction using the following steps: + +#### 1. Get Token Contract Address + +```java +Copy code +String tokenContractAddress = client.getContractAddressByName(privateKey, Sha256.getBytesSha256("AElf.ContractNames.Token")); +``` + +#### 2. Set Recipient Address + +```java +Client.Address.Builder to = Client.Address.newBuilder(); +to.setValue(ByteString.copyFrom(Base58.decodeChecked("7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz"))); +Client.Address toObj = to.build(); +``` + +#### 3. Create Transfer Input + +```java +TokenContract.TransferInput.Builder paramTransfer = TokenContract.TransferInput.newBuilder(); +paramTransfer.setTo(toObj); +paramTransfer.setSymbol("ELF"); +paramTransfer.setAmount(1000000000); +paramTransfer.setMemo("transfer in demo"); +TokenContract.TransferInput paramTransferObj = paramTransfer.build(); +``` + +#### 4. Generate and Sign Transaction + +```java +String ownerAddress = client.getAddressFromPrivateKey(privateKey); +Transaction.Builder transactionTransfer = client.generateTransaction(ownerAddress, tokenContractAddress, "Transfer", paramTransferObj.toByteArray()); +Transaction transactionTransferObj = transactionTransfer.build(); +transactionTransfer.setSignature(ByteString.copyFrom(ByteArrayHelper.hexToByteArray(client.signTransaction(privateKey, transactionTransferObj)))); +transactionTransferObj = transactionTransfer.build(); +``` + +#### 5. Send Transaction + +```java +SendTransactionInput sendTransactionInputObj = new SendTransactionInput(); +sendTransactionInputObj.setRawTransaction(Hex.toHexString(transactionTransferObj.toByteArray())); +SendTransactionOutput sendResult = client.sendTransaction(sendTransactionInputObj); +``` + +#### 6. Query Execution Results + +```java +Thread.sleep(4000); +TransactionResultDto transactionResult = client.getTransactionResult(sendResult.getTransactionId()); +System.out.println(transactionResult.getStatus()); +``` + +#### 7. Query Account Balance + +```java +Client.Address.Builder owner = Client.Address.newBuilder(); +owner.setValue(ByteString.copyFrom(Base58.decodeChecked(ownerAddress))); +Client.Address ownerObj = owner.build(); + +TokenContract.GetBalanceInput.Builder paramGetBalance = TokenContract.GetBalanceInput.newBuilder(); +paramGetBalance.setSymbol("ELF"); +paramGetBalance.setOwner(ownerObj); +TokenContract.GetBalanceInput paramGetBalanceObj = paramGetBalance.build(); + +Transaction.Builder transactionGetBalance = client.generateTransaction(ownerAddress, tokenContractAddress, "GetBalance", paramGetBalanceObj.toByteArray()); +Transaction transactionGetBalanceObj = transactionGetBalance.build(); +String signature = client.signTransaction(privateKey, transactionGetBalanceObj); +transactionGetBalance.setSignature(ByteString.copyFrom(ByteArrayHelper.hexToByteArray(signature))); +transactionGetBalanceObj = transactionGetBalance.build(); + +ExecuteTransactionDto executeTransactionDto = new ExecuteTransactionDto(); +executeTransactionDto.setRawTransaction(Hex.toHexString(transactionGetBalanceObj.toByteArray())); +String transactionGetBalanceResult = client.executeTransaction(executeTransactionDto); + +TokenContract.GetBalanceOutput balance = TokenContract.GetBalanceOutput.getDefaultInstance().parseFrom(ByteArrayHelper.hexToByteArray(transactionGetBalanceResult)); +System.out.println(balance.getBalance()); +``` + +This guide provides basic steps to interact with an AElf node using the aelf-sdk.java library. For more detailed information and advanced usage, please refer to the repository documentation. + + + +## Web API + +You can see how the Web API of the node works at `{chainAddress}/swagger/index.html`. For example, if you are using a local address, it would be: `http://127.0.0.1:1235/swagger/index.html`. + +The usage of these methods is based on the AElfClient instance. So, if you don’t have one, please create it: + +```java +import AElf.Client.Service; + +// Create a new instance of AElfClient, change the URL if needed +AElfClient client = new AElfClient("http://127.0.0.1:1235"); +``` + + +### GetChainStatus + +Get the current status of the blockchain. + +**Web API path**: `/api/blockChain/chainStatus` + +**Parameters**: None + +**Returns**: ChainStatusDto + +- `ChainId` - String +- `Branches` - HashMap `` +- `NotLinkedBlocks` - HashMap `` +- `LongestChainHeight` - long +- `LongestChainHash` - String +- `GenesisBlockHash` - String +- `GenesisContractAddress` - String +- `LastIrreversibleBlockHash` - String +- `LastIrreversibleBlockHeight` - long +- `BestChainHash` - String +- `BestChainHeight` - long + +**Example**: + +```java +client.getChainStatus(); +``` + + +### GetContractFileDescriptorSet + +Get the protobuf definitions related to a contract. + +**Web API path**: `/api/blockChain/contractFileDescriptorSet` + +**Parameters:** + +- `contractAddress` - String (address of a contract) + +**Returns**: `byte[]` + +**Example**: + +```java +client.getContractFileDescriptorSet(address); +``` + + + +### GetBlockHeight + +Get the current best height of the chain. + + +**Web API path**: `/api/blockChain/blockHeight` + +**Parameters:**: None + +**Returns**: `long` + +**Example**: + +```java +client.getBlockHeight(); +``` + + + +### GetBlock + +Get block information by block hash. + +**Web API path**: `/api/blockChain/block` + +**Parameters:** + +- `blockHash` - String +- `includeTransactions` - boolean (true to include transaction ids list in the block, false otherwise) + +**Returns**: `BlockDto` + + - `json` + - `BlockHash` - String + - `Header` - BlockHeaderDto + - `PreviousBlockHash` - String + - `MerkleTreeRootOfTransactions` - String + - `MerkleTreeRootOfWorldState` - String + - `Extra` - String + - `Height` - long + - `Time` - Date + - `ChainId` - String + - `Bloom` - String + - `SignerPubkey` - String + - `Body` - BlockBodyDto + - `TransactionsCount` - int + - `Transactions` - List + - `transactionId` - String + + +**Example**: + +```java +client.getBlockByHash(blockHash); +``` + + +### GetBlockByHeight + +**Web API path**: `/api/blockChain/blockByHeight` + +**Parameters:** + +- `blockHeight` - long +- `includeTransactions` - boolean (true to include transaction ids list in the block, false otherwise) + +**Returns**: `BlockDto` + + - `json` + - `BlockHash` - String + - `Header` - BlockHeaderDto + - `PreviousBlockHash` - String + - `MerkleTreeRootOfTransactions` - String + - `MerkleTreeRootOfWorldState` - String + - `Extra` - String + - `Height` - long + - `Time` - Date + - `ChainId` - String + - `Bloom` - String + - `SignerPubkey` - String + - `Body` - BlockBodyDto + - `TransactionsCount` - int + - `Transactions` - List + - `transactionId` - String + + +**Example**: + +```java +client.getBlockByHeight(height); +``` + + +### GetTransactionResult + +**Web API path**: `/api/blockChain/transactionResult` + +**Parameters:** + +- `transactionId` - String + +**Returns**: `TransactionResultDto` + + - `json` + - `TransactionId` - String + - `Status` - String + - `Logs` - List + - `Address` - String + - `Name` - String + - `Indexed` - List + - `NonIndexed` - String + - `Bloom` - String + - `BlockNumber` - Number + - `Transaction` - List + - `From` - String + - `To` - String + - `RefBlockNumber` - Number + - `RefBlockPrefix` - String + - `MethodName` - String + - `Params` - json + - `Signature` - String + - `ReadableReturnValue` - json + - `Error` - String + +**Example**: + +```java +client.getTransactionResult(transactionId); +``` + + +### GetTransactionResults + +**Web API path**: `/api/blockChain/transactionResults` + +**Parameters:** + +- `blockHash` - String +- `offset` - int +- `limit` - int + +**Returns**: `List` - The array of transaction results + +**Example**: + +```java +client.getTransactionResults(blockHash, 0, 10); +``` + + +### GetTransactionPoolStatus + +**Web API path**: `/api/blockChain/transactionPoolStatus` + +**Parameters:**: None + +**Returns**: `TransactionPoolStatusOutput` + +- `Queued` - int +- `Validated` - int + +**Example**: + +```java +client.getTransactionPoolStatus(); +``` + + +### SendTransaction + +**Web API path**: `/api/blockChain/sendTransaction` + +**Method**: POST + +**Parameters:** + +- `SendTransactionInput` - Serialization of data into protobuf format: + - `RawTransaction` - String + +**Returns**: `SendTransactionOutput` + +- `TransactionId` - String + +**Example**: + +```java +client.sendTransaction(input); +``` + + +### SendRawTransaction + +**Web API path**: `/api/blockChain/sendTransaction` + +**Method**: POST + +**Parameters:** + +- `SendRawTransactionInput` - Serialization of data into protobuf format: + - `Transaction` - String + - `Signature` - String + - `ReturnTransaction` - boolean + +**Returns**: `SendRawTransactionOutput` + + - `TransactionId` - String + - `Transaction` - TransactionDto + + +**Example**: + +```java +client.sendRawTransaction(input); +``` + + +### SendTransactions + +Broadcast multiple transactions. + +**Web API path**: `/api/blockChain/sendTransactions` + +**Method**: POST + +**Parameters:** + +- `SendTransactionsInput` - Serialization of data into protobuf format: + - `RawTransactions` - String + +**Returns**: `List` + +**Example**: + +```java +client.sendTransactions(input); +``` + + + +### CreateRawTransaction + +Create an unsigned serialized transaction. + +**Web API path**: `/api/blockChain/rawTransaction` + +**Method**: POST + +**Parameters:** + +- `CreateRawTransactionInput` + - `From` - String + - `To` - String + - `RefBlockNumber` - long + - `RefBlockHash` - String + - `MethodName` - String + - `Params` - String + +**Returns**: `CreateRawTransactionOutput` - Serialization of data into protobuf format: + +- `RawTransaction` - String + +**Example**: + +```java +client.createRawTransaction(input); +``` + + +### ExecuteTransaction + +**Web API path**: `/api/blockChain/executeTransaction` + +**Method**: POST + +**Parameters:** + +- `ExecuteTransactionDto` - Serialization of data into protobuf format: + - `RawTransaction` - String + +**Returns**: `String` + +**Example**: + +```java +client.executeTransaction(input); +``` + + +### ExecuteRawTransaction + +**Web API path**: `/api/blockChain/executeRawTransaction` + +**Method**: POST + +**Parameters:** + +- `ExecuteRawTransactionDto` - Serialization of data into protobuf format: + - `RawTransaction` - String + - `Signature` - String + +**Returns**: `String` + +**Example**: + +```java +client.executeRawTransaction(input); +``` + + + +### GetPeers + +Get peer information about the connected network nodes. + +**Web API path**: `/api/net/peers` + +**Parameters:** + +- `withMetrics` - boolean + +**Returns**: `List` + +- `IpAddress` - String +- `ProtocolVersion` - int +- `ConnectionTime` - long +- `ConnectionStatus` - String +- `Inbound` - boolean +- `BufferedTransactionsCount` - int +- `BufferedBlocksCount` - int +- `BufferedAnnouncementsCount` - int +- `NodeVersion` - String +- `RequestMetrics` - List`` +- `RoundTripTime` - long +- `MethodName` - String +- `Info` - String +- `RequestTime` - String + + +**Example**: + +```java +client.getPeers(false); +``` + + +### AddPeer + +Attempts to add a node to the connected network nodes. + +**Web API path**: `/api/net/peer` + +**Method**: POST + +**Parameters:** + +- `AddPeerInput` + - `Address` - String + +**Returns**: `boolean` + +**Example**: + +```java +client.addPeer("127.0.0.1:7001"); +``` + + + +### RemovePeer + +Attempts to remove a node from the connected network nodes. + +**Web API path**: `/api/net/peer` + +**Method**: DELETE + +**Parameters:** + +- `Address` - String + +**Returns**: `boolean` + +**Example**: + +```java +client.removePeer("127.0.0.1:7001"); +``` + + +### CalculateTransactionFee + +Estimate transaction fee. + +**Web API path**: `/api/blockChain/calculateTransactionFee` + +**Method**: POST + +**Parameters:** + +- `CalculateTransactionFeeInput` + - `RawTransaction` - String + +**Returns**: `CalculateTransactionFeeOutput` + +- `Success` - boolean +- `TransactionFee` - HashMap`` +- `ResourceFee` - HashMap`` + +**Example**: + +```java +CalculateTransactionFeeOutput output = client.calculateTransactionFee(input); +``` + + + +### GetNetworkInfo + +**Web API path**: `/api/net/networkInfo` + +**Parameters:** None + +**Returns**: `NetworkInfoOutput` + +- `Version` - String +- `ProtocolVersion` - int +- `Connections` - int + +**Example**: + +```java +client.getNetworkInfo(); +``` + + +## AElf Client + + +### IsConnected + +Verify whether this SDK successfully connects to the chain. + + +**Parameters:** None + +**Returns**: `boolean` + + +**Example**: + +```java +client.isConnected(); +``` + + +### GetGenesisContractAddress + + +**Parameters:** None + +**Returns**: `String` + +**Example**: + +```java +client.getGenesisContractAddress(); +``` + + +### GetContractAddressByName + +Get the address of a contract by the given contract name hash. + + +**Parameters:**: + +- `privateKey` - String +- `contractNameHash` - byte[] + + +**Returns**: `String` + +**Example**: + +```java +client.getContractAddressByName(privateKey, contractNameHash); +``` + + +### GenerateTransaction + +Build a transaction from the input parameters. + +**Parameters:** + +- `from` - String +- `to` - String +- `methodName` - String +- `input` - byte[] + + +**Returns**: `Transaction` + +**Example**: + +```java +client.generateTransaction(from, to, methodName, input); +``` + + +### GetFormattedAddress + +Convert the Address to the displayed string: `symbol_base58-string_base58-String-chain-id`. + +**Parameters:** + +- `privateKey` - String +- `address` - String + +**Returns**: `String` + +**Example**: + +```java +client.getFormattedAddress(privateKey, address); +``` + + +### SignTransaction + +**Parameters:** + +- `privateKeyHex` - String +- `transaction` - Transaction + +**Returns**: `String` + +**Example**: + +```java +client.signTransaction(privateKeyHex, transaction); +``` + + +### GetAddressFromPubKey + +**Parameters:** + +- `pubKey` - String + +**Returns**: `String` + +**Example**: + +```java +client.getAddressFromPubKey(pubKey); +``` + + +### GetAddressFromPrivateKey + +**Parameters:** + +- `privateKey` - String + +**Returns**: `String` + +**Example**: + +```java +client.getAddressFromPrivateKey(privateKey); +``` + + +### GenerateKeyPairInfo + +**Parameters:** None + +**Returns**: `KeyPairInfo` + +- `PrivateKey` - String +- `PublicKey` - String +- `Address` - String + +**Example**: + +```java +client.generateKeyPairInfo(); +``` + + +## Supports + +- JDK1.8+ +- Log4j2.6.2 \ No newline at end of file diff --git a/docs/Developer Tools/Chain Sdk/javascript-sdk.md b/docs/Developer Tools/Chain Sdk/javascript-sdk.md new file mode 100644 index 00000000..20c9c1b5 --- /dev/null +++ b/docs/Developer Tools/Chain Sdk/javascript-sdk.md @@ -0,0 +1,602 @@ +--- +sidebar_position: 1 +title: Javascript SDK +description: Javascript SDK +--- + +# aelf-sdk.js - aelf JavaScript API + +## Introduction + +The `aelf-sdk.js` library for aelf is similar to web3.js for Ethereum. It allows you to interact with a local or remote aelf node using an HTTP connection. + +This guide will help you install and use `aelf-sdk.js`, with an API reference and examples. + +For more details, check out the repository: [aelf-sdk.js](https://github.com/AElfProject/aelf-web3.js). + + +## Adding aelf-sdk.js + +First, you need to add `aelf-sdk.js` to your project. You can do this using the following methods + + +### Using npm + +```base +npm install aelf-sdk +``` + +### Pure JS + +Add the script link in your HTML: + +```javascript + +``` + +Then, create an aelf instance and set a provider. + +```javascript +// In Node.js +const AElf = require('aelf-sdk'); +const aelf = new AElf(new AElf.providers.HttpProvider('http://127.0.0.1:8000')); + +// In browser +// +``` + + +## Examples + +You can find more examples in the `./examples` directory. + +### Create Instance + +```javascript +import AElf from 'aelf-sdk'; + +// Create a new instance of AElf +const aelf = new AElf(new AElf.providers.HttpProvider('http://127.0.0.1:1235')); +``` + +### Create or Load a Wallet + +```javascript +// Create a new wallet +const newWallet = AElf.wallet.createNewWallet(); + +// Load a wallet by private key +const privateKeyWallet = AElf.wallet.getWalletByPrivateKey('your-private-key'); + +// Load a wallet by mnemonic +const mnemonicWallet = AElf.wallet.getWalletByMnemonic('your-mnemonic'); +``` + + +### Get a System Contract Address + +```javascript +const tokenContractName = 'AElf.ContractNames.Token'; +let tokenContractAddress; + +(async () => { + // Get chain status + const chainStatus = await aelf.chain.getChainStatus(); + // Get genesis contract address + const GenesisContractAddress = chainStatus.GenesisContractAddress; + // Get genesis contract instance + const zeroContract = await aelf.chain.contractAt(GenesisContractAddress, newWallet); + // Get contract address by the read-only method 'GetContractAddressByName' of genesis contract + tokenContractAddress = await zeroContract.GetContractAddressByName.call(AElf.utils.sha256(tokenContractName)); +})(); +``` + + +### Get a Contract Instance + +```javascript +const wallet = AElf.wallet.createNewWallet(); +let tokenContract; + +// Async method +(async () => { + tokenContract = await aelf.chain.contractAt(tokenContractAddress, wallet); +})(); + +// Promise method +aelf.chain.contractAt(tokenContractAddress, wallet) + .then(result => { + tokenContract = result; + }); + +// Callback method +aelf.chain.contractAt(tokenContractAddress, wallet, (error, result) => { + if (error) throw error; + tokenContract = result; +}); +``` + + +### Use Contract Instance + +How to use a contract instance. You can call methods in two ways: read-only and send transaction. + +```javascript +(async () => { + // Read-only method: Get the balance of an address + const balanceResult = await tokenContract.GetBalance.call({ + symbol: "ELF", + owner: "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz" + }); + console.log(balanceResult); + /** + { + "symbol": "ELF", + "owner": "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz", + "balance": "1000000000000" + } + */ + + // Send transaction method: Transfer tokens + const transactionId = await tokenContract.Transfer({ + symbol: "ELF", + to: "7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz", + amount: "1000000000", + memo: "transfer in demo" + }); + console.log(transactionId); + /** + { + "TransactionId": "123123" + } + */ +})(); +``` + + +### Change the Node Endpoint + +```javascript +import AElf from 'aelf-sdk'; + +const aelf = new AElf(new AElf.providers.HttpProvider('http://127.0.0.1:1235')); +aelf.setProvider(new AElf.providers.HttpProvider('http://127.0.0.1:8000')); +``` + + +## Web API + +You can access the Web API of your aelf node at `{chainAddress}/swagger/index.html`. + +For example, if your local node address is `http://127.0.0.1:1235`, you can view the Web API at `http://127.0.0.1:1235/swagger/index.html`. + +The methods below use an instance of aelf. If you don't have one, create it as shown: + +```javascript +import AElf from 'aelf-sdk'; + +// Create a new instance of AElf, change the URL if needed +const aelf = new AElf(new AElf.providers.HttpProvider('http://127.0.0.1:1235')); +``` + +### 1. Get Chain Status + +Get the current status of the blockchain. + +- **Web API Path**: `/api/blockChain/chainStatus` +- **Method**: GET +- **Parameters**: None +- **Returns**: Object with details like ChainId, LongestChainHeight, GenesisContractAddress, etc. + + +#### Example: + +```javascript +aelf.chain.getChainStatus() + .then(res => { + console.log(res); + }); +``` + + +### 2. Get Contract File Descriptor Set + +Get the protobuf definitions related to a contract. + +- **Web API Path**: `/api/blockChain/contractFileDescriptorSet` +- **Method**: GET +- **Parameters**: `contractAddress` (String) +- **Returns**: String. + + +#### Example: + +```javascript +aelf.chain.getContractFileDescriptorSet(contractAddress) + .then(res => { + console.log(res); + }); +``` + + +### 3. Get Block Height + +Get the current best height of the chain. + + +- **Web API Path**: `/api/blockChain/blockHeight` +- **Method**: GET +- **Parameters**: None +- **Returns**: Number. + + +#### Example: + +```javascript +aelf.chain.getBlockHeight() + .then(res => { + console.log(res); + }); +``` + + +### 4. Get Block + +Get block information by block hash. + +- **Web API Path**: `/api/blockChain/block` +- **Method**: GET +- **Parameters**: `contractAddress` (String) + - **`blockHash`** (String) + - **`includeTransactions`** (Boolean) +- **Returns**: object with block details + + +#### Example: + +```javascript +aelf.chain.getBlock(blockHash, false) + .then(res => { + console.log(res); + }); +``` + + +### 5. Get Block By Height + +Get block information by block height. + +- **Web API Path**: `/api/blockChain/blockByHeight` +- **Method**: GET +- **Parameters**: + - **`blockHash`** (String) + - **`includeTransactions`** (Boolean) +- **Returns**: Object with block details + + +#### Example: + +```javascript +aelf.chain.getBlockByHeight(12, false) + .then(res => { + console.log(res); + }); +``` + +### 6. Get Transaction Result + + +- **Web API Path**: `/api/blockChain/transactionResult` +- **Method**: GET +- **Parameters**: `transactionId` (String) +- **Returns**: Object with transaction details + + +#### Example: + +```javascript +aelf.chain.getTxResult(transactionId) + .then(res => { + console.log(res); + }); +``` + +### 7. Get Multiple Transaction Results + + +- **Web API Path**: `/api/blockChain/transactionResults` +- **Method**: GET +- **Parameters**: + - **`blockHash`** (String) + - **`offset`** (Number) + - **`limit`** (Number) +- **Returns**: Array of transaction result objects + + +#### Example: + +```javascript +aelf.chain.getTxResults(blockHash, 0, 2) + .then(res => { + console.log(res); + }); +``` + +### 8. Get Transaction Pool Status + + +- **Web API Path**: `/api/blockChain/transactionPoolStatus` +- **Method**: GET +- **Parameters**: None +- **Returns**: Object with transaction pool status + + +### 9. Send Transaction + + +- **Web API Path**: `/api/blockChain/sendTransaction` +- **Method**: POST +- **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) +- **Returns**: Transaction ID + + +### 10. Send Multiple Transactions + + +- **Web API Path**: `/api/blockChain/sendTransactions` +- **Method**: POST +- **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) +- **Returns**: Transaction IDs + + +### 11. Call Read-Only Method + + +- **Web API Path**: `/api/blockChain/callReadOnly` +- **Method**: POST +- **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) +- **Returns**: Method call result + + +### 12. Get Peers + + +- **Web API Path**: `/api/net/peers` +- **Method**: GET +- **Parameters**: `withMetrics` (Boolean) +- **Returns**: Array of peer info + + +### 13. Add Peer + + +- **Web API Path**: `/api/net/peer` +- **Method**: POST +- **Parameters**: `Object` (Address string) +- **Returns**: Status + + +### 14. Remove Peer + + +- **Web API Path**: `/api/net/peer` +- **Method**: DELETE +- **Parameters**: `address` (String) +- **Returns**: Status + + +### 15. Send Multiple Transactions + + +- **Web API Path**: `/api/blockChain/calculateTransactionFee` +- **Method**: POST +- **Parameters**: `CalculateTransactionFeeInput` (Object with RawTransaction string) +- **Returns**: `CalculateTransactionFeeOutput` (Object with fee details) + +#### Example + +```javascript +aelf.chain.calculateTransactionFee(rawTransaction) + .then(res => { + console.log(res); + }); +``` + +### 16. Network Info + + +- **Web API Path**: `/api/net/networkInfo` +- **Method**: GET +- **Parameters**: None +- **Returns**: Network connection info + + + +## AElf.wallet + +`AElf.wallet` is a static property of `AElf`. + + +### 1. createNewWallet + +**Returns:** + +- **Object** + + - **`mnemonic - String`**: The mnemonic phrase for the wallet. + - **`BIP44Path - String`**: The BIP44 path, formatted as m/purpose’/coin_type’/account’/change/address_index. + - **`childWallet - Object`**: The Hierarchical Deterministic (HD) wallet object. + - **`keyPair - String`**: The elliptic curve (EC) key pair. + - **`privateKey - String`**: The private key for the wallet. + - **`address - String`**: The wallet address. + +#### Example: + +```javascript +import AElf from 'aelf-sdk'; +const wallet = AElf.wallet.createNewWallet(); +console.log(wallet); +``` + + +### 2. getWalletByMnemonic + +Retrieves a wallet using a mnemonic phrase. + + +**Parameters:** + +- **`mnemonic - String`**: The mnemonic phrase of the wallet. + +**Returns:** + +- **`Object`**: The complete wallet object. + + +#### Example: + +```javascript +const wallet = AElf.wallet.getWalletByMnemonic(mnemonic); +console.log(wallet); +``` + + +### 3. getWalletByPrivateKey + +Retrieves a wallet using a private key. + +**Parameters:** + +- **`privateKey - String`**: The mnemonic phrase of the wallet. + +**Returns:** + +- **`Object`**: The complete wallet object, with an empty mnemonic. + + +#### Example: + +```javascript +const wallet = AElf.wallet.getWalletByPrivateKey(privateKey); +console.log(wallet); +``` + + +### 4. signTransaction + +Signs a transaction using the wallet's key pair. + +**Parameters:** + +- **`rawTxn - String`**: The raw transaction data. +- **`keyPair - String`**: The key pair to sign the transaction. + +**Returns:** + +- **`Object`**: The signed transaction object. + + +#### Example: + +```javascript +const result = AElf.wallet.signTransaction(rawTxn, keyPair); +console.log(result); +``` + + +### 5. AESEncrypt + +Encrypts a string using the AES algorithm. + +**Parameters:** + +- **`input - String`**: The input string to encrypt. +- **`password - String`**: The password to use for encryption. + +**Returns:** + +- **`String`**: The encrypted string. + + + +### 6. AESDecrypt + +Decrypts a string using the AES algorithm. + +**Parameters:** + +- **`input - String`**: The encrypted string. +- **`password - String`**: The password used for encryption. + +**Returns:** + +- **`String`**: The decrypted string. + +These are the detailed functions and their usages for the AElf.wallet API. If you have any specific questions or need further clarification, feel free to ask! + + + +## AElf.pbjs + +Reference to protobuf.js. For detailed usage, refer to the [protobuf.js documentation](https://github.com/protobufjs/protobuf.js). + + +## AElf.pbUtils + +Provides basic format methods for aelf. For detailed code, see `src/utils/proto.js`. + + +### AElf.utils + +Contains utility methods for aelf. For detailed code, see `src/utils/utils.js`. + + +### Check address + +Example to check if an address is valid using `base58` utility from aelf. + +#### Example: + +```javascript +const AElf = require('aelf-sdk'); +const { base58 } = AElf.utils; + +try { + base58.decode('$address'); // replace '$address' with actual address + console.log('Valid address'); +} catch (error) { + console.error('Invalid address', error); +} +``` + +## AElf.version + +```javascript +import AElf from 'aelf-sdk'; +console.log(AElf.version); // outputs the version, e.g., 3.2.23 +``` + + +## Requirements + +To use aelf SDK, you need: + +- [Node.js](https://nodejs.org/en) +- [NPM](https://www.npmjs.com/) + + +## Support + +![browsers](https://img.shields.io/badge/browsers-latest%202%20versions-brightgreen.svg) +![node](https://img.shields.io/badge/node-%3E=10-green.svg) + + + +## About contributing + +Read out [contributing guide] + + +## About Version + +AElf SDK follows Semantic Versioning. For more details, refer to [semver.org](https://semver.org/). diff --git a/docs/Developer Tools/Chain Sdk/php-skd.md b/docs/Developer Tools/Chain Sdk/php-skd.md new file mode 100644 index 00000000..ee769c4a --- /dev/null +++ b/docs/Developer Tools/Chain Sdk/php-skd.md @@ -0,0 +1,674 @@ +--- +sidebar_position: 5 +title: PHP SDK +description: PHP SDK +--- + +# aelf-sdk.php - aelf PHP API + +## Introduction +aelf-sdk.php for aelf is similar to web.js for Ethereum. It consists of libraries that enable interaction with a local or remote aelf node via HTTP. + +This documentation will guide you through the installation and usage of aelf-sdk.php, with examples included. For more information, visit the [aelf-sdk.php repository](https://github.com/AElfProject/aelf-sdk.php). + +## Adding aelf PHP SDK +To install the library via Composer, run the following commands in your console: + +```sh +composer require aelf/aelf-sdk dev-dev +composer require curl/curl +``` + +If you cloned the SDK directly, you must install Composer and run it in the root directory: + +```json +{ + "require": { + "aelf/aelf-sdk": "dev-dev" + } +} +``` + +## Examples + +### 1. Create an Instance +Create a new instance of AElf and connect to an AELF chain node. Using this instance, you can call the AElf APIs. + +```php +require_once 'vendor/autoload.php'; +use AElf\AElf; + +$url = 'http://127.0.0.1:8000'; +$aelf = new AElf($url); +``` + +### 2. Get a System Contract Address +Get a system contract address. For example, to get the address of `AElf.ContractNames.Token`: + +```php +require_once 'vendor/autoload.php'; +use AElf\AElf; +use AElf\Protobuf\Generated\Hash; + +$url = 'http://127.0.0.1:8000'; +$aelf = new AElf($url); + +$privateKey = 'cd86ab6347d8e52bbbe8532141fc59ce596268143a308d1d40fedf385528b458'; +$bytes = new Hash(); +$bytes->setValue(hex2bin(hash('sha256', 'AElf.ContractNames.Token'))); +$contractAddress = $aelf->GetContractAddressByName($privateKey, $bytes); +``` + +### 3. Send a Transaction +Get the contract address and then send a transaction. + +```php +require_once 'vendor/autoload.php'; +use AElf\AElf; +use BitWasp\Bitcoin\Key\PrivateKeyFactory; + +$url = 'http://127.0.0.1:8000'; +$aelf = new AElf($url); + +$privateKey = 'cd86ab6347d8e52bbbe8532141fc59ce596268143a308d1d40fedf385528b458'; +$aelfEcdsa = new BitcoinECDSA(); +$aelfEcdsa->setPrivateKey($privateKey); +$publicKey = $aelfEcdsa->getUncompressedPubKey(); +$address = $aelfEcdsa->hash256(hex2bin($publicKey)); +$address = $address . substr($aelfEcdsa->hash256(hex2bin($address)), 0, 8); +$base58Address = $aelfEcdsa->base58_encode($address); + +$params = new Hash(); +$params->setValue(hex2bin(hash('sha256', 'AElf.ContractNames.Vote'))); +$methodName = "GetContractAddressByName"; +$toAddress = $aelf->getGenesisContractAddress(); + +$transactionObj = $aelf->generateTransaction($base58Address, $toAddress, $methodName, $params); +$signature = $aelf->signTransaction($privateKey, $transactionObj); +$transactionObj->setSignature(hex2bin($signature)); + +$executeTransactionDtoObj = ['RawTransaction' => bin2hex($transactionObj->serializeToString())]; +$result = $aelf->sendTransaction($executeTransactionDtoObj); +print_r($result); +``` + +## Web API +---------- + +You can access the Web API of your aelf node at: + +```base +{chainAddress}/swagger/index.html +``` + +**Example**: For a local address: `http://127.0.0.1:1235/swagger/index.html` + +Before using the methods, make sure you have an instance of AElf: + +```php +require_once 'vendor/autoload.php'; +use AElf\AElf; + +$url = '127.0.0.1:8000'; +$aelf = new AElf($url); +``` + + +### 1. Get Chain Status + +- **API Path**: `/api/blockChain/chainStatus` + +- **Parameters**: None + +- **Returns**: Array with chain status details + +- **Example** : + +```php +$chainStatus = $aelf->getChainStatus(); +print_r($chainStatus); +``` + + + +### 2. Get Block Height + +- **API Path**: `/api/blockChain/blockHeight` + +- **Parameters**: None + +- **Returns**: Integer + +- **Example** : + +```php +$height = $aelf->getBlockHeight(); +print($height); +``` + + +### 3. Get Block by Hash + +- **API Path**: `/api/blockChain/block` + +- **Parameters**: + + - `block_hash` (String) + - `include_transactions` (Boolean) + +- **Returns**: Array with block information + +- **Example** : + +```php +$block = $aelf->getBlockByHeight(1, true); +$block2 = $aelf->getBlockByHash($block['BlockHash'], false); +print_r($block2); +``` + + +### 4. Get Block by Height + +- **API Path**: `/api/blockChain/blockByHeight` + +- **Parameters**: + + - `block_height` (Number) + - `include_transactions` (Boolean) + +- **Returns**: Array with block information + +- **Example** : + +```php +$block = $aelf->getBlockByHeight(1, true); +print_r($block); +``` + + +### 5. Get Transaction Result + +- **API Path**: `/api/blockChain/transactionResult` + +- **Parameters**: + + - `transactionId` (String) + +- **Returns**: Object with transaction result details + +- **Example** : + +```php +$block = $aelf->getBlockByHeight(1, true); +$transactionResult = $aelf->getTransactionResult($block['Body']['Transactions'][0]); +print_r($transactionResult); +``` + + +### 6. Get Multiple Transaction Results + +- **API Path**: `/api/blockChain/transactionResults` + +- **Parameters**: + + - `blockHash` (String) + - `offset` (Number) + - `limit` (Number) + +- **Returns**: List of transaction result objects + +- **Example** : + +```php +$block = $aelf->getBlockByHeight(1, true); +$transactionResults = $aelf->getTransactionResults($block['Body']); +print_r($transactionResults); +``` + + +### 7. Get Transaction Pool Status + +- **API Path**: `/api/blockChain/transactionPoolStatus` + +- **Example** : + +```php +$status = $aelf->getTransactionPoolStatus(); +print_r($status); +``` + + +### 8. Send Transaction + +- **API Path**: `/api/blockChain/sendTransaction` + +- **Method**: POST + +- **Parameters**: + + - `transaction` (String) + +- **Example** : + +```php +$params = new Hash(); +$params->setValue(hex2bin(hash('sha256', 'AElf.ContractNames.Vote'))); +$transaction = buildTransaction($aelf->getGenesisContractAddress(), 'GetContractAddressByName', $params); +$executeTransactionDtoObj = ['RawTransaction' => bin2hex($transaction->serializeToString())]; +$result = $aelf->sendTransaction($executeTransactionDtoObj); +print_r($result); +``` + + +### 9. Send Multiple Transactions + +- **API Path**: `/api/blockChain/sendTransactions` + +- **Method**:POST + +- **Parameters**: + + - `transactions` (String) + +- **Example** : + +```php +$paramsList = [$params1, $params2]; +$rawTransactionsList = []; +foreach ($paramsList as $param) { + $transactionObj = buildTransaction($toAddress, $methodName, $param); + $rawTransactions = bin2hex($transactionObj->serializeToString()); + array_push($rawTransactionsList, $rawTransactions); +} +$sendTransactionsInputs = ['RawTransactions' => implode(',', $rawTransactionsList)]; +$listString = $aelf->sendTransactions($sendTransactionsInputs); +print_r($listString); +``` + + +### 10. Get Peers + +- **API Path**: `/api/net/peers` + +- **Example** : + +```php +print_r($aelf->getPeers(true)); +``` + + +### 11. Add Peer + +- **API Path**: `/api/net/peer` + +- **Method**: POST + +- **Parameters**: + + - `peer_address` (String) + +- **Example** : + +```php +$aelf->addPeer($url); +``` + + +### 12. Remove Peer + +- **API Path**: `/api/net/peer` + +- **Parameters**: + + - `peer_address` (String) + +- **Example** : + +```php +$aelf->removePeer($url); +``` + + +### 13. Create Raw Transaction + +- **API Path**: `/api/blockchain/rawTransaction` + +- **Method**: POST + +- **Parameters**: + + - `transaction` (Array) + +- **Returns**: Array with the raw transaction hex string + +- **Example** : + +```php +$status = $aelf->getChainStatus(); +$params = base64_encode(hex2bin(hash('sha256', 'AElf.ContractNames.Consensus'))); +$param = array('value' => $params); +$transaction = [ + "from" => $aelf->getAddressFromPrivateKey($privateKey), + "to" => $aelf->getGenesisContractAddress(), + "refBlockNumber" => $status['BestChainHeight'], + "refBlockHash" => $status['BestChainHash'], + "methodName" => "GetContractAddressByName", + "params" => json_encode($param) +]; +$rawTransaction = $aelf->createRawTransaction($transaction); +print_r($rawTransaction); +``` + + +### 14. Send Raw Transaction + +- **API Path**: `/api/blockchain/sendRawTransaction` + +- **Parameters**: + + - `Transaction` (raw transaction) + - `Signature` (signature) + - `ReturnTransaction` (indicates whether to return transaction) + +- **Example** : + +```php +$rawTransaction = $aelf->createRawTransaction($transaction); +$transactionId = hash('sha256', hex2bin($rawTransaction['RawTransaction'])); +$sign = $aelf->getSignatureWithPrivateKey($privateKey, $transactionId); +$transaction = array('Transaction' => $rawTransaction['RawTransaction'], 'signature' => $sign, 'returnTransaction' => true); +$execute = $aelf->sendRawTransaction($transaction); +print_r($execute); +``` + + + +### 15. Execute Raw Transaction + +- **API Path**: `/api/blockchain/executeRawTransaction` + +- **Method**: POST + +- **Parameters**: + + - `RawTransaction` (raw transaction) + - `Signature` (signature) + + +- **Example** : + +```php +$rawTransaction = $aelf->createRawTransaction($transaction); +$transactionId = hash('sha256', hex2bin($rawTransaction['RawTransaction'])); +$sign = $aelf->getSignatureWithPrivateKey($privateKey, $transactionId); +$transaction = array('RawTransaction' => $rawTransaction['RawTransaction'], 'signature' => $sign); +$execute = $aelf->executeRawTransaction($transaction); +print_r($execute); +``` + + +### 16. Get Merkle Path by Transaction ID + +- **API Path**: `/api/blockchain/merklePathByTransactionId` + +- **Parameters**: + + - `transactionId` (String) + +- **Example** : + +```php +$block = $aelf->getBlockByHeight(1, true); +$merklePath = $aelf->getMerklePathByTransactionId($block['Body']['Transactions'][0]); +print_r($merklePath); +``` + + +### 17. Calculate Transaction Fee + +- **API Path**: `/api/blockChain/calculateTransactionFee` + +- **Method**: POST + +- **Parameters**: + + - `CalculateTransactionFeeInput` (Object) + +- **Returns**: `CalculateTransactionFeeOutput (Object)` + +- **Example** : + +```php +$calculateTransactionFeeInputParam = [ + "rawTransaction" => $rawTransactionInput, +]; +$result = $aelf->calculateTransactionFee($calculateTransactionFeeInputParam); +print_r($result); +``` + + +### 18. Get Network Info + +- **API Path**: `/api/net/networkInfo` + +- **Example** : + +```php +print_r($aelf->getNetworkInfo()); +``` + + +### 19. Get Contract File Descriptor Set + +- **API Path**: `/api/blockchain/contractFileDescriptorSet` + +- **Example** : + +```php +$aelf = new AElf($url); + +$blockDto = $aelf->getBlockByHeight($blockHeight, false); +$transactionResultDtoList = $aelf->getTransactionResults($blockDto['BlockHash'], 0, 10); +foreach ($transactionResultDtoList as $v) { + $request = $aelf->getContractFileDescriptorSet($v['Transaction']['To']); + print_r($request); +} +``` + + +### 20. Get Task Queue Status + +- **API Path**: `/api/blockchain/taskQueueStatus` + +- **Example** : + +```php +$aelf = new AElf($url); + +$taskQueueStatus = $aelf->getTaskQueueStatus(); +print_r($taskQueueStatus); +``` + + +### 21. Execute Transaction + +- **API Path**: `/api/blockchain/executeTransaction` + +- **Example** : + +```php +$aelf = new AElf($url); + +$methodName = "GetNativeTokenInfo"; +$bytes = new Hash(); +$bytes->setValue(hex2bin(hash('sha256', 'AElf.ContractNames.Token'))); +$toAddress = $aelf->GetContractAddressByName($privateKey, $bytes); +$param = new Hash(); +$param->setValue(''); +$transaction = $aelf->generateTransaction($fromAddress, $toAddress, $methodName, $param); +$signature = $aelf->signTransaction($privateKey, $transaction); +$transaction->setSignature(hex2bin($signature)); +$executeTransactionDtoObj = ['RawTransaction' => bin2hex($transaction->serializeToString())]; +$response = $aelf->executeTransaction($executeTransactionDtoObj); +$tokenInfo = new TokenInfo(); +$tokenInfo->mergeFromString(hex2bin($response)); +``` + + + +## Other Tool Kit + +AElf supplies some APIs to simplify development. + +### 1. Get Chain Id + +```php +$aelf = new AElf($url); + +$chainId = $aelf->getChainId(); +print_r($chainId); +``` + + +### 2. Generate Transaction + +```php +$aelf = new AElf($url); + +$param = new Hash(); +$param->setValue(''); +$transaction = $aelf->generateTransaction($fromAddress, $toAddress, $methodName, $param); +``` + + +### 3. Sign Transaction + +```php +$aelf = new AElf($url); + +$transaction = $aelf->generateTransaction($fromAddress, $toAddress, $methodName, $param); +$signature = $aelf->signTransaction($privateKey, $transaction); +``` + + +### 4. Get Genesis Contract Address + +```php +$aelf = new AElf($url); + +$genesisContractAddress = $aelf->getGenesisContractAddress(); +print_r($genesisContractAddress); +``` + + +### 5. Get Address From PubKey +Calculate the account address according to the public key. + +```php +$aelf = new AElf($url); + +$pubKeyAddress = $aelf->getAddressFromPubKey('04166cf4be901dee1c21f3d97b9e4818f229bec72a5ecd56b5c4d6ce7abfc3c87e25c36fd279db721acf4258fb489b4a4406e6e6e467935d06990be9d134e5741c'); +print_r($pubKeyAddress); +``` + + +### 6. Get Formatted Address +Convert the address to the displayed string: symbol_base58-string_base58-string_chain_id. + +```php +$aelf = new AElf($url); + +$addressVal = $aelf->getFormattedAddress($privateKey, $base58Address); +print_r($addressVal); +``` + + +### 7. Generate Key Pair Info +Generate a new key pair using ECDSA. + +```php +$aelf = new AElf($url); + +$pairInfo = $aelf->generateKeyPairInfo(); +print_r($pairInfo); +``` + + +### 8. Get Contract Address By Name + +```php +$aelf = new AElf($url); + +$bytes = new Hash(); +$bytes->setValue(hex2bin(hash('sha256', 'AElf.ContractNames.Token'))); +$contractAddress = $aelf->GetContractAddressByName($privateKey, $bytes); +print_r($contractAddress); +``` + + +### 9. Get Address From Private Key + +```php +$aelf = new AElf($url); + +$address = $aelf->getAddressFromPrivateKey($privateKey); +print_r($address); +``` + + +### 10. Get Signature With Private Key + +```php +$aelf = new AElf($url); + +$sign = $aelf->getSignatureWithPrivateKey($privateKey, $transactionId); +print_r($sign); +``` + + +### 11. Is Connected + +```php +$aelf = new AElf($url); + +$isConnected = $this->aelf->isConnected(); +print_r($isConnected); +``` + + +### 12. Get Transaction Fees +Get the transaction fee from the transaction result. + +```php +$aelf = new AElf($url); + +$block = $aelf->getBlockByHeight(1, true); +$transactionResult = $aelf->getTransactionResult($block['Body']['Transactions'][0]); +$transactionFees = $aelf->getTransactionFees($transactionResult); +print_r($transactionFees); +``` + +## AElf.version + +```php +Copy code +$aelf = new AElf($url); + +$version = $aelf->version; +``` + + +## Requirements + +- [**php**](https://php.orgwe67y8re8hufr54ff4ed3ed32ws2d3crf4cfsx2ws2e33333333333333333333333333333333dr34cf4c2q4cfuj7ji8o87hb6fv4d3ed3/) + + + +## About contributing +Read out [contributing guide] + +## About Version + +[https://semver.org/](https://semver.org/) + + diff --git a/docs/Developer Tools/Chain Sdk/python-sdk.md b/docs/Developer Tools/Chain Sdk/python-sdk.md new file mode 100644 index 00000000..f2e71d82 --- /dev/null +++ b/docs/Developer Tools/Chain Sdk/python-sdk.md @@ -0,0 +1,850 @@ +--- +sidebar_position: 6 +title: Python SDK +description: Python SDK +--- + +# aelf-sdk.py - aelf Python API + +## Introduction + +The `aelf-sdk.py` is the Python equivalent of `web3.js` for Ethereum. It is a collection of libraries that allow you to interact with a local or remote aelf node using an HTTP connection. + +This documentation will guide you through the installation and usage of `aelf-sdk.py`, providing detailed API references with examples. For more information, you can check out the [aelf-sdk.py repository](https://github.com/AElfProject/aelf-sdk.py). + +## Adding aelf-sdk.py + +To start using `aelf-sdk.py` in your project, you need to install the package. This can be done using pip: + +```sh +pip install aelf-sdk +``` + +After installation, you need to create an instance of `AElf` using a node’s URL: + +```python +from aelf import AElf + +chain = AElf('http://127.0.0.1:8000') +``` + + +## Examples + +You can find more examples in the `./test` directory of the repository. + +### 1. Create an Instance + +To create a new instance of `AElf` and connect to an aelf chain node, use the following code. With this instance, you can call various APIs on aelf. + +```python +from aelf import AElf + +# Create a new instance of AElf +aelf = AElf('http://127.0.0.1:8000') +``` + + +### 2. Get a System Contract Address + +To get a system contract address, for example, the `AElf.ContractNames.Token`, use the following code: + +```python +from aelf import AElf + +aelf = AElf('http://127.0.0.1:8000') + +# Get the genesis contract address +genesis_contract_address = aelf.get_genesis_contract_address_string() + +# Get the contract address +# The get_system_contract_address method calls 'GetContractAddressByName' in the genesis contract to get other contracts' addresses +multi_token_contract_address = aelf.get_system_contract_address('AElf.ContractNames.Token') +``` + + +### 3. Send a Transaction + +To send a transaction, first get the contract address and then use the following steps: + +```python +from aelf import AElf, PrivateKey, CrossChainTransferInput + +url = 'http://127.0.0.1:8000' + +# Create a new instance of AElf +aelf = AElf(url) + +# Generate the private key +private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa' +private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string))) + +# Create input, the type is generated by protoc +cross_chain_transfer_input = CrossChainTransferInput() + +# Generate the transaction +transaction = aelf.create_transaction(to_address, method_name, params.SerializeToString()) + +# Sign the transaction with the user's private key +aelf.sign_transaction(private_key, transaction) + +# Execute the transaction +aelf.execute_transaction(transaction) +``` + +By following these instructions, you can effectively interact with the aelf blockchain using the `aelf-sdk.py` library. For more detailed examples and information, please refer to the [aelf-sdk.py repository](https://github.com/AElfProject/aelf-sdk.py). + + + +## Web API + +You can view how the Web API of the node works at `http://{chainAddress}/swagger/index.html`. + +For example, if your local address is `http://127.0.0.1:1235`, you can access it at `http://127.0.0.1:1235/swagger/index.html`. + +Before using these methods, make sure you have an `AElf` instance. If not, create one as shown below: + + +```python +from aelf import AElf + +# Create a new instance of AElf, change the URL if needed +aelf = AElf('http://127.0.0.1:8000') +``` + + +### 1. Get Chain Status + +**Web API Path**: `/api/blockChain/chainStatus` + +**Parameters**: None + +**Returns**: JSON + + - `ChainId` - String + - `Branches` - JSON + - `NotLinkedBlocks` - JSON + - `LongestChainHeight` - Number + - `LongestChainHash` - String + - `GenesisBlockHash` - String + - `GenesisContractAddress` - String + - `LastIrreversibleBlockHash` - String + - `LastIrreversibleBlockHeight` - Number + - `BestChainHash` - String + - `BestChainHeight` - Number + +**Example**: + +```python +aelf = AElf(url) +chain_status = aelf.get_chain_status() +print('# get_chain_status', chain_status) +``` + + +### 2. Get Block Height + +**Web API Path**: `/api/blockChain/blockHeight` + +**Parameters**: None + +**Returns**: Number + +**Example**: + +```python +aelf = AElf(url) +block_height = aelf.get_block_height() +print('# get_block_height', block_height) +``` + + +### 3. Get Block + +**Web API Path**: /api/blockChain/block + +**Parameters**: None + + - `block_hash` - String + - `include_transactions` - Boolean (true to include transaction IDs list, false otherwise) + +**Returns**: JSON + + - `BlockHash` - String + - `Header` - JSON + - `PreviousBlockHash` - String + - `MerkleTreeRootOfTransactions` - String + - `MerkleTreeRootOfWorldState` - String + - `Extra` - List + - `Height` - Number + - `Time` - JSON + - `ChainId` - String + - `Bloom` - String + - `SignerPubkey` - String + - `Body` - JSON + - `TransactionsCount` - Number + - `Transactions` - List + +**Example**: + +```python +aelf = AElf(url) +block = aelf.get_block(blockHash) +print('# get_block', block) +``` + + +### 4. Get Block by Height + +**Web API Path**: /api/blockChain/blockByHeight + +**Parameters**: + + - `block_height` - Number + - `include_transactions` - Boolean (true to include transaction IDs list, false otherwise) + +**Returns**: JSON + + - `BlockHash` - String + - `Header` - JSON + - `PreviousBlockHash` - String + - `MerkleTreeRootOfTransactions` - String + - `MerkleTreeRootOfWorldState` - String + - `Extra` - List + - `Height` - Number + - `Time` - JSON + - `ChainId` - String + - `Bloom` - String + - `SignerPubkey` - String + - `Body` - JSON + - `TransactionsCount` - Number + - `Transactions` - List + +**Example**: + +```python +aelf = AElf(url) +block_by_height = aelf.get_block_by_height(12, False) +print('# get_block_by_height', block_by_height) +``` + + +### 5. Get Transaction Result + +**Web API Path**: /api/blockChain/transactionResult + +**Parameters**: + + - `transactionId` - String + +**Returns**: JSON + + - `TransactionId` - String + - `Status` - String + - `Logs` - List + - `Address` - String + - `Name` - String + - `Indexed` - List + - `NonIndexed` - String + - `Bloom` - String + - `BlockNumber` - Number + - `Transaction` - List + - `From` - Number + - `To` - Number + - `RefBlockNumber` - Number + - `RefBlockPrefix` - String + - `MethodName` - String + - `Params` - JSON + - `Signature` - String + - `ReadableReturnValue` - JSON + - `Error` - String + +**Example**: + +```python +aelf = AElf(url) +transaction_result = aelf.get_transaction_result(transactionId) +print('# get_transaction_result', transaction_result) +``` + + +### 6. Get Transaction Results + +**Web API Path**: /api/blockChain/transactionResults + +**Parameters**: + + - `blockHash` - String + - `offset` - Number + - `limit` - Number + + +**Returns**: List of transaction result objects + +**Example**: + +```python +aelf = AElf(url) +transaction_results = aelf.get_transaction_results(blockHash, 0, 2) +print('# get_transaction_results', transaction_results) +``` + + + +### 7. Get Transaction Pool Status + +**Web API Path**: /api/blockChain/transactionPoolStatus + +**Example**: + +```python +aelf = AElf(url) +tx_pool_status = aelf.get_transaction_pool_status() +print('# get_transaction_pool_status', tx_pool_status) +``` + + +### 8. Send Transaction + +**Web API Path**: `/api/blockChain/sendTransaction` + +**Method**: POST + +**Parameters**: + + - `transaction` - String (serialized data) + +**Example**: + +```python +aelf = AElf(url) +current_height = aelf.get_block_height() +block = aelf.get_block_by_height(current_height, include_transactions=False) +transaction = Transaction() +transaction.to_address.CopyFrom(aelf.get_system_contract_address("AElf.ContractNames.Consensus")) +transaction.ref_block_number = current_height +transaction.ref_block_prefix = bytes.fromhex(block['BlockHash'])[0:4] +transaction.method_name = 'GetCurrentMinerList' +transaction = aelf.sign_transaction(private_key, transaction) +result = aelf.send_transaction(transaction.SerializePartialToString().hex()) +print('# send_transaction', result) +``` + + + +### 9. Send Transactions + +**Web API Path**: `/api/blockChain/sendTransaction` + +**Method**: POST + +**Parameters**: + + - `transactions` - String (serialized data) + +**Example**: + +```python +aelf = AElf(url) +current_height = aelf.get_block_height() +block = aelf.get_block_by_height(current_height, include_transactions=False) +transaction1 = Transaction().SerializePartialToString().hex() +transaction2 = Transaction().SerializePartialToString().hex() +result = aelf.send_transaction(transaction1 + ',' + transaction2) +print('# send_transactions', result) +``` + + +### 10. Get Peers + +**Web API Path**: `/api/net/peers` + +**Parameters**: + + - `blockHash` - String + - `offset` - Number + - `limit` - Number + +**Example**: + +```python +aelf = AElf(url) +peers = aelf.get_peers() +print('# get_peers', peers) +``` + + +### 11. Add Peer + +**Web API Path**: `/api/net/peers` + +**Method**: POST + +**Parameters**: + + - `peer_address` - String (peer’s endpoint) + +**Example**: + +```python +aelf = AElf(url) +add_peer = aelf.add_peer(endpoint) +print('# add_peer', add_peer) +``` + + + +### 12. Remove Peer + +**Web API Path**: `/api/net/peer?address=` + +**Method**: POST + +**Parameters**: + + - `peer_address` - String (peer’s endpoint) + +**Example**: + +```python +aelf = AElf(url) +remove_peer = aelf.remove_peer(address) +print('# remove_peer', remove_peer) +``` + +### 13. Create Raw Transaction + +**Web API Path**: `/api/blockchain/rawTransaction` + +**Method**: POST + +**Parameters**: + + - `transaction` - JSON format transaction + +**Returns**: JSON + + - `RawTransaction` - hex string bytes generated by transaction information + +**Example**: + +```python +aelf = AElf(url) +transaction = { + "From": aelf.get_address_string_from_public_key(public_key), + "To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"), + "RefBlockNumber": 0, + "RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa", + "MethodName": "GetCurrentMinerList", + "Params": '{}' +} +raw_transaction = aelf.create_raw_transaction(transaction) +print('# create_raw_transaction', raw_transaction) +``` + + +### 14. Send Raw Transaction + +**Web API Path**: `/api/blockchain/sendRawTransaction` + +**Method**: POST + +**Parameters**: + + - `Transaction` - raw transaction + - `Signature` - signature + - `ReturnTransaction` - indicates whether to return the transaction + +**Example**: + +```python +aelf = AElf(url) + +# Create the raw transaction +raw_transaction = aelf.create_raw_transaction({ + "From": aelf.get_address_string_from_public_key(public_key), + "To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"), + "RefBlockNumber": 0, + "RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa", + "MethodName": "GetCurrentMinerList", + "Params": '{}' +}) + +# Sign the raw transaction +signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction'])) + +# Create the transaction payload +transaction_2 = { + "Transaction": raw_transaction['RawTransaction'], + 'Signature': signature.hex(), + 'ReturnTransaction': True +} + +# Send the raw transaction +result = aelf.send_raw_transaction(transaction_2) +print('# send_raw_transaction', result) +``` + +### 15. Execute Raw Transaction + +**Web API Path**: `/api/blockchain/executeRawTransaction` + +**Method**: POST + +**Parameters**: + + - `RawTransaction` - raw transaction + - `Signature` - signature + +**Example**: + +```python +aelf = AElf(url) + +# Create the raw transaction +raw_transaction = aelf.create_raw_transaction({ + "From": aelf.get_address_string_from_public_key(public_key), + "To": aelf.get_system_contract_address_string("AElf.ContractNames.Consensus"), + "RefBlockNumber": 0, + "RefBlockHash": "b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa", + "MethodName": "GetCurrentMinerList", + "Params": '{}' +}) + +# Sign the raw transaction +signature = private_key.sign_recoverable(bytes.fromhex(raw_transaction['RawTransaction'])) + +# Create the transaction payload +transaction_1 = { + "RawTransaction": raw_transaction['RawTransaction'], + "Signature": signature.hex() +} + +# Execute the raw transaction +result = aelf.execute_raw_transaction(transaction_1) +print('# execute_raw_transaction', result) +``` + + +### 16. Get Merkle Path + +**Web API Path**: `/api/blockchain/merklePathByTransactionId?transactionId=` + +**Method**: POST + +**Parameters**: + + - `transactionId` - String + +**Example**: + +```python +aelf = AElf(url) + +transaction_id = "your-transaction-id" +merkle_path = aelf.get_merkle_path(transaction_id) +print('# get_merkle_path', merkle_path) +``` + + +### 16. Calculate Transaction Fee + +**Web API Path**: `/api/blockchain/calculateTransactionFee` + +**Method**: POST + +**Parameters**: + + - `CalculateTransactionFeeInput` - JSON with the following structure: + - `RawTransaction` - String + +**Returns**: JSON with the following structure: + + - `Success` - Boolean + - `TransactionFee` - Array + - `ResourceFee` - Array + +**Example**: + +```python +aelf = AElf(url) + +calculate_transaction_fee_input = { + "RawTransaction": raw_transaction['RawTransaction'] +} + +calculate_transaction_fee_output = aelf.calculate_transaction_fee(calculate_transaction_fee_input) +print('# calculate_transaction_fee', calculate_transaction_fee_output) +``` + + + +### 16. Calculate Transaction Fee + +**Web API Path**: `/api/net/networkInfo` + +**Method**: POST + +**Example**: + +```python +aelf = AElf(url) + +network_info = aelf.get_network_info() +print('# get_network_info', network_info) +``` + + + +## AElf.client + +Use the API to see detailed results. + +### 1. get_genesis_contract_address_string + +Returns the zero contract address. + +**Example:** + +```python +aelf = AElf(url) + +genesis_contract_address = aelf.get_genesis_contract_address_string() +``` + + +### 2. get_system_contract_address + +**Parameters:** + +- `contract_name` - String: system contract’s name + +**Returns:** + +Address: system contract’s address + +**Example:** + +```python +aelf = AElf(url) + +multi_token_contract_address = aelf.get_system_contract_address('AElf.ContractNames.Token') +``` + + +### 3. get_system_contract_address_string + +**Parameters:** + +- `contract_name` - String: system contract’s name + +**Returns:** + +String: system contract’s address + +**Example:** + +```python +aelf = AElf(url) + +multi_token_contract_address_string = aelf.get_system_contract_address_string('AElf.ContractNames.Token') +``` + + +### 4. create_transaction + +**Parameters:** + +- `to_address` - Address or String: target contract’s address +- `method_name` - String: method name +- `params` - String: serialize parameters into String + +**Example:** + +```python +aelf = AElf(url) + +params = Hash() +params.value = hashlib.sha256(contract_name.encode('utf8')).digest() +transaction = aelf.create_transaction(genesisContractAddress, 'GetContractAddressByName', params.SerializeToString()) +``` + + +### 5. sign_transaction + +Sign a transaction with the user’s private key. + +**Parameters:** + +- `private_key` - String: user’s private key +- `transaction` - Transaction: transaction + +**Example:** + +```python +aelf = AElf(url) + +to_address_string = aelf.get_genesis_contract_address_string() +params = Hash() +params.value = hashlib.sha256(contract_name.encode('utf8')).digest() +transaction = aelf.create_transaction(to_address_string, 'GetContractAddressByName', params.SerializeToString()) +transaction = aelf.sign_transaction(private_key, transaction) +``` + + +### 6. get_address_from_public_key + +Generate an address from a public key. + +**Parameters:** + +- `public_key` - bytes: user’s public key + +**Returns:** + +- Address + +**Example:** + +```python +aelf = AElf(url) + +address = aelf.get_address_from_public_key(public_key) +``` + + +### 7. get_address_string_from_public_key + +Generate an address string from a public key. + +**Parameters:** + +- `public_key` - bytes: user’s public key + +**Returns:** + +- String + +**Example:** + +```python +aelf = AElf(url) + +address = aelf.get_address_string_from_public_key(public_key) +``` + + + +### 8. get_chain_id + + +**Returns:** + +- Number + +**Example:** + +```python +aelf = AElf(url) + +chain_id = aelf.get_chain_id() +print('# get_chain_id', chain_id) +``` + + + +### 9. get_formatted_address + +**Parameters:** + +- `address` - Address: address + +**Returns:** + +- String + +**Example:** + +```python +aelf = AElf(url) + +address = aelf.chain.get_system_contract_address("AElf.ContractNames.Consensus") +formatted_address = aelf.get_formatted_address(address) +print('formatted address', formatted_address) +``` + + +### 9. is_connected + +Check whether the node is connected. + +**Example:** + +```python +aelf = AElf(url) + +is_connected = aelf.is_connected() +``` + + + +## Tookkits.py + +AElfToolkit Encapsulate AElf and user’s private key. It simplifies the procedures of sending some transactions. You can find it in src/aelf/toolkits.py. + + +### Create a Toolkit + +Create a Toolkit with AElfToolkit. + +```python +from aelf import AElfToolkit + +# generate the private key +private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa' +private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string))) + +# create a toolkit +toolkit = AElfToolkit('http://127.0.0.1:8000', private_key) +``` + + +### Send a Transaction + +Send a CrossChainTransfer transaction using AElfToolkit. + +```python +from aelf import AElfToolkit + +# generate the private key +private_key_string = 'b344570eb80043d7c5ae9800c813b8842660898bf03cbd41e583b4e54af4e7fa' +private_key = PrivateKey(bytes(bytearray.fromhex(private_key_string))) + +# create input, the type is generated by protoc +cross_chain_transfer_input = CrossChainTransferInput() + +# AElfToolkit simplifies this transaction execution. +# create a toolkit +toolkit = AElfToolkit('http://127.0.0.1:8000', private_key) +toolkit.cross_chain_transfer(to_address_string, symbol, amount, memo, to_chain_id) +``` + + + +## Requirements + +- Python +- Docker + + +## Support + +- Node + +## About Contributing + +Read out [contributing guide]. + +## About Version + +[https://semver.org/](https://semver.org/) \ No newline at end of file diff --git a/docs/References/Web API/Chain API.md b/docs/References/Web API/Chain API.md new file mode 100644 index 00000000..9adcc45f --- /dev/null +++ b/docs/References/Web API/Chain API.md @@ -0,0 +1,1158 @@ +# AELF API 1.0 + +## Chain API + +### Get information about a given block by block hash. Optionally with the list of its transactions. + +```http +GET /api/blockChain/block +``` + +| Parameter | Type | Description | Default | +| :-------------------- | :-------- | :-------------------------------- | :-------- | +| `blockHash` | `string` | Block hash _(optional)_ | | +| `includeTransactions` | `boolean` | Include transactions _(optional)_ | `"false"` | + +#### Responses + +- **200**: Success (`BlockDto`) + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Get information about a given block by block height. Optionally with the list of its transactions. + +```http +GET /api/blockChain/blockByHeight +``` + +| Parameter | Type | Description | Default | +| :-------------------- | :-------- | :-------------------------------- | :-------- | +| `blockHeight` | `integer` | Block height _(optional)_ | | +| `includeTransactions` | `boolean` | Include transactions _(optional)_ | `"false"` | + +#### Responses + +- **200**: Success (`BlockDto`) + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Get the height of the current chain. + +```http +GET /api/blockChain/blockHeight +``` + +#### Responses + +- **200**: Success (integer, int64) + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Get the current state about a given block. + +```http +GET /api/blockChain/blockState +``` + +| Parameter | Type | Description | +| :---------- | :------- | :---------------------- | +| `blockHash` | `string` | Block hash _(optional)_ | + +#### Responses + +- **200**: Success (`BlockStateDto`) + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Get the current status of the block chain. + +```http +GET /api/blockChain/chainStatus +``` + +#### Responses + +- **200**: Success (`ChainStatusDto`) + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Get the protobuf definitions related to a contract. + +```http +GET /api/blockChain/contractFileDescriptorSet +``` + +| Parameter | Type | Description | +| :-------- | :------- | :---------------------------- | +| `address` | `string` | Contract address _(optional)_ | + +#### Responses + +- **200**: Success (string, byte) + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Execute a raw transaction. + +```http +POST /api/blockChain/executeRawTransaction +``` + +#### Parameters + +| Type | Name | Schema | +| :------- | :------ | :-------------------------------------- | +| **Body** | `input` | `ExecuteRawTransactionDto` _(optional)_ | + +#### Responses + +| HTTP Code | Description | Schema | +| :-------: | :---------- | :----- | +| **200** | Success | string | + +#### Consumes + +- `application/json-patch+json; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/*+json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Call a read-only method on a contract. + +```http +POST /api/blockChain/executeTransaction +``` + +#### Parameters + +| Type | Name | Schema | +| :------- | :------ | :----------------------------------- | +| **Body** | `input` | `ExecuteTransactionDto` _(optional)_ | + +#### Responses + +| HTTP Code | Description | Schema | +| :-------: | :---------- | :----- | +| **200** | Success | string | + +#### Consumes + +- `application/json-patch+json; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/*+json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Get the merkle path of a transaction. + +```http +GET /api/blockChain/merklePathByTransactionId +``` + +#### Parameters + +| Type | Name | Schema | +| :-------: | :-------------- | :------------------ | +| **Query** | `transactionId` | string _(optional)_ | + +#### Responses + +| HTTP Code | Description | Schema | +| :-------: | :---------- | :-------------- | +| **200** | Success | `MerklePathDto` | + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Creates an unsigned serialized transaction. + +```http +POST /api/blockChain/rawTransaction +``` + +#### Parameters + +| Type | Name | Schema | +| :------- | :------ | :--------------------------------------- | +| **Body** | `input` | `CreateRawTransactionInput` _(optional)_ | + +#### Responses + +| HTTP Code | Description | Schema | +| :-------: | :---------- | :--------------------------- | +| **200** | Success | `CreateRawTransactionOutput` | + +#### Consumes + +- `application/json-patch+json; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/*+json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Send a transaction. + +```http +POST /api/blockChain/sendRawTransaction +``` + +#### Parameters + +| Type | Name | Schema | +| :------- | :------ | :------------------------------------- | +| **Body** | `input` | `SendRawTransactionInput` _(optional)_ | + +#### Responses + +| HTTP Code | Description | Schema | +| :-------: | :---------- | :------------------------- | +| **200** | Success | `SendRawTransactionOutput` | + +#### Consumes + +- `application/json-patch+json; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/*+json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Produces + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +#### Tags + +- **BlockChain** + +--- + +### Broadcast a Transaction + +**POST** `/api/blockChain/sendTransaction` + +**Parameters** + +| Type | Name | Schema | Description | Required | +| -------- | ------- | ---------------------- | ----------- | -------- | +| **Body** | `input` | `SendTransactionInput` | - | No | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ----------------------- | +| **200** | Success | `SendTransactionOutput` | + +**Consumes** + +- `application/json-patch+json; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/*+json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- BlockChain + +--- + +### Broadcast Multiple Transactions + +**POST** `/api/blockChain/sendTransactions` + +**Parameters** + +| Type | Name | Schema | Description | Required | +| -------- | ------- | ----------------------- | ----------- | -------- | +| **Body** | `input` | `SendTransactionsInput` | - | No | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ------------ | +| **200** | Success | `` | + +**Consumes** + +- `application/json-patch+json; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/*+json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- BlockChain + +--- + +### Estimate Transaction Fee + +**POST** `/api/blockChain/calculateTransactionFee` + +**Parameters** + +| Type | Name | Schema | Description | Required | +| -------- | ------- | ------------------------------ | ----------- | -------- | +| **Body** | `input` | `CalculateTransactionFeeInput` | - | No | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ------------------------------- | +| **200** | Success | `CalculateTransactionFeeOutput` | + +**Consumes** + +- `application/json-patch+json; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/*+json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- BlockChain + +--- + +### Get the Current Status of a Transaction + +**GET** `/api/blockChain/transactionResult` + +**Parameters** + +| Type | Name | Schema | Description | Required | +| --------- | --------------- | -------- | -------------- | -------- | +| **Query** | `transactionId` | `string` | Transaction ID | No | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ---------------------- | +| **200** | Success | `TransactionResultDto` | + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- BlockChain + +--- + +### Get the Transaction Pool Status + +**GET** `/api/blockChain/transactionPoolStatus` + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | -------------------------------- | +| **200** | Success | `GetTransactionPoolStatusOutput` | + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- BlockChain + +--- + +### Get the Current Status of a Transaction + +**GET** `/api/blockChain/transactionResult` + +**Parameters** + +| Type | Name | Description | Schema | +| --------- | ----------------- | -------------------------- | ------ | +| **Query** | **transactionId** | _Optional_. Transaction ID | string | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ---------------------- | +| **200** | Success | `TransactionResultDto` | + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- BlockChain + +--- + +### Get Multiple Transaction Results + +**GET** `/api/blockChain/transactionResults` + +**Parameters** + +| Type | Name | Description | Schema | Default | +| --------- | ------------- | --------------------------------- | --------------- | ------- | +| **Query** | **blockHash** | _Optional_. Block hash | string | | +| **Query** | **limit** | _Optional_. Limit results | integer (int32) | `10` | +| **Query** | **offset** | _Optional_. Offset for pagination | integer (int32) | `0` | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ------------------------ | +| **200** | Success | `TransactionResultDto[]` | + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- BlockChain + +--- + +### Net API + +#### Get Network Information + +**GET** `/api/net/networkInfo` + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ---------------------- | +| **200** | Success | `GetNetworkInfoOutput` | + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- Net + +--- + +#### Add a Node to Connected Network Nodes + +**POST** `/api/net/peer` + +**Parameters** + +| Type | Name | Description | Schema | +| -------- | --------- | -------------------------- | -------------- | +| **Body** | **input** | _Optional_. Add peer input | `AddPeerInput` | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ------- | +| **200** | Success | boolean | + +| **401** | Unauthorized| | + +**Security** + +- Basic Authentication + +**Consumes** + +- `application/json-patch+json; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/*+json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- Net + +--- + +#### Remove a Node from Connected Network Nodes + +**DELETE** `/api/net/peer` + +**Parameters** + +| Type | Name | Description | Schema | +| --------- | ----------- | ---------------------- | ------ | +| **Query** | **address** | _Optional_. IP address | string | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ------- | +| **200** | Success | boolean | + +| **401** | Unauthorized| | + +**Security** + +- Basic Authentication + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- Net + +--- + +#### Get Peer Info about Connected Network Nodes + +**GET** `/api/net/peers` + +**Parameters** + +| Type | Name | Description | Schema | Default | +| --------- | --------------- | --------------------------- | ------- | --------- | +| **Query** | **withMetrics** | _Optional_. Include metrics | boolean | `"false"` | + +**Responses** + +| HTTP Code | Description | Schema | +| --------- | ----------- | ----------- | +| **200** | Success | `PeerDto[]` | + +**Produces** + +- `text/plain; v=1.0` +- `application/json; v=1.0` +- `text/json; v=1.0` +- `application/x-protobuf; v=1.0` + +**Tags** + +- BlockChain + +--- + +## Definitions + +### AddPeerInput + +##### Description + +Represents the input parameters for adding a peer. + +#### Schema + +| Name | Description | Schema | +| --------- | ----------- | ------ | +| Address\* | IP address | string | + +### BlockBodyDto + +#### Description + +Represents the body of a block, including transactions and transaction count. + +#### Schema + +| Name | Schema | +| ----------------- | ---------------- | +| Transactions\* | < string > array | +| TransactionsCount | integer (int32) | + +### BlockDto + +#### Description + +Represents a block, including its hash, body, header, and size. + +#### Schema + +| Name | Schema | +| --------- | ---------------- | +| BlockHash | string | +| Body\* | `BlockBodyDto` | +| Header\* | `BlockHeaderDto` | +| BlockSize | integer (int32) | + +### BlockHeaderDto + +#### Description + +Represents the header of a block, including various metadata. + +#### Schema + +| Name | Schema | +| -------------------------------- | ------------------ | +| Bloom | string | +| ChainId | string | +| Extra | string | +| Height | integer (int64) | +| MerkleTreeRootOfTransactions | string | +| MerkleTreeRootOfWorldState | string | +| MerkleTreeRootOfTransactionState | string | +| PreviousBlockHash | string | +| SignerPubkey | string | +| Time | string (date-time) | + +### BlockStateDto + +#### Description + +Represents the state of a block, including hash, height, changes, deletes, and previous hash. + +#### Schema + +| Name | Schema | +| ------------ | ---------------------- | +| BlockHash | string | +| BlockHeight | integer (int64) | +| Changes\* | < string, string > map | +| Deletes\* | < string > array | +| PreviousHash | string | + +### ChainStatusDto + +#### Description + +Represents the status of a blockchain network, including chain details and block heights. + +#### Schema + +| Name | Schema | +| ----------------------------- | ------------------------------- | +| BestChainHash\* | string | +| BestChainHeight\* | integer (int64) | +| Branches\* | < string, integer (int64) > map | +| ChainId\* | string | +| GenesisBlockHash\* | string | +| GenesisContractAddress | string | +| LastIrreversibleBlockHash\* | string | +| LastIrreversibleBlockHeight\* | integer (int64) | +| LongestChainHash\* | string | +| LongestChainHeight\* | integer (int64) | +| NotLinkedBlocks\* | < string, string > map | + +### CreateRawTransactionInput + +#### Description + +Represents the input parameters for creating a raw transaction. + +#### Schema + +| Name | Description | Schema | +| ---------------- | -------------------------- | --------------- | +| From\* | From address | string | +| MethodName\* | Contract method name | string | +| Params\* | Contract method parameters | string | +| RefBlockHash\* | Reference block hash | string | +| RefBlockNumber\* | Reference block height | integer (int64) | +| To\* | To address | string | + +### CreateRawTransactionOutput + +#### Description + +Represents the output of creating a raw transaction. + +#### Schema + +| Name | Schema | +| -------------- | ------ | +| RawTransaction | string | + +### ExecuteRawTransactionDto + +#### Description + +Represents the input parameters for executing a raw transaction. + +#### Schema + +| Name | Description | Schema | +| ---------------- | --------------- | ------ | +| RawTransaction\* | Raw transaction | string | +| Signature\* | Signature | string | + +### ExecuteTransactionDto + +#### Description + +Represents the input parameters for executing a transaction. + +#### Schema + +| Name | Description | Schema | +| ---------------- | --------------- | ------ | +| RawTransaction\* | Raw transaction | string | + +### GetNetworkInfoOutput + +#### Description + +Represents the output of getting network information. + +#### Schema + +| Name | Description | Schema | +| ----------------- | ----------------- | --------------- | +| Connections\* | Total connections | integer (int32) | +| ProtocolVersion\* | Network protocol | integer (int32) | +| Version\* | Node version | string | + +### GetTransactionPoolStatusOutput + +#### Description + +Represents the output of getting transaction pool status. + +#### Schema + +| Name | Schema | +| ----------- | --------------- | +| Queued\* | integer (int32) | +| Validated\* | integer (int32) | + +### LogEventDto + +#### Description + +Represents a log event. + +#### Schema + +| Name | Schema | +| ------------ | ---------------- | +| Address\* | string | +| Indexed\* | < string > array | +| Name\* | string | +| NonIndexed\* | string | + +### MerklePathDto + +#### Description + +Represents a Merkle path. + +#### Schema + +| Name | Schema | +| ----------------- | ----------------------------- | +| MerklePathNodes\* | < `MerklePathNodeDto` > array | + +### MerklePathNodeDto + +#### Description + +Represents a node in a Merkle path. + +#### Schema + +| Name | Schema | +| ----------------- | ------- | +| Hash\* | string | +| IsLeftChildNode\* | boolean | + +### MinerInRoundDto + +#### Description + +Represents information about a miner in a round. + +#### Schema + +| Name | Schema | +| ------------------------------ | ---------------------------- | +| ActualMiningTimes\* | < string (date-time) > array | +| ExpectedMiningTime\* | string (date-time) | +| ImpliedIrreversibleBlockHeight | integer (int64) | +| InValue\* | string | +| MissedBlocks\* | integer (int64) | +| Order\* | integer (int32) | +| OutValue\* | string | +| PreviousInValue\* | string | +| ProducedBlocks\* | integer (int64) | +| ProducedTinyBlocks\* | integer (int32) | + +### PeerDto + +#### Description + +Represents information about a peer node. + +#### Schema + +| Name | Schema | +| ---------------------------- | ------------------------- | +| BufferedAnnouncementsCount\* | integer (int32) | +| BufferedBlocksCount\* | integer (int32) | +| BufferedTransactionsCount\* | integer (int32) | +| ConnectionTime\* | integer (int64) | +| Inbound\* | boolean | +| IpAddress\* | string | +| ProtocolVersion\* | integer (int32) | +| RequestMetrics\* | < `RequestMetric` > array | +| ConnectionStatus\* | string | +| NodeVersion\* | string | + +### RequestMetric + +#### Description + +Represents metrics for a request. + +#### Schema + +| Name | Schema | +| --------------- | --------------- | +| Info\* | string | +| MethodName\* | string | +| RequestTime\* | `Timestamp` | +| RoundTripTime\* | integer (int64) | + +### RoundDto + +#### Description + +Represents a round in the blockchain. + +#### Schema + +| Name | Schema | +| --------------------------------------- | --------------------------------- | +| ConfirmedIrreversibleBlockHeight\* | integer (int64) | +| ConfirmedIrreversibleBlockRoundNumber\* | integer (int64) | +| ExtraBlockProducerOfPreviousRound\* | string | +| IsMinerListJustChanged\* | boolean | +| RealTimeMinerInformation\* | < string, `MinerInRoundDto` > map | +| RoundId\* | integer (int64) | +| RoundNumber\* | integer (int64) | +| TermNumber\* | integer (int64) | + +### SendRawTransactionInput + +#### Description + +Represents the input parameters for sending a raw transaction. + +#### Schema + +| Name | Description | Schema | +| ------------------- | --------------- | ------- | +| ReturnTransaction\* | Return detail | boolean | +| Signature\* | Signature | string | +| Transaction\* | Raw transaction | string | + +### SendRawTransactionOutput + +#### Description + +Represents the output of sending a raw transaction. + +#### Schema + +| Name | Schema | +| --------------- | ---------------- | +| Transaction | `TransactionDto` | +| TransactionId\* | string | + +### SendTransactionInput + +#### Description + +Represents the input parameters for sending a transaction. + +#### Schema + +| Name | Description | Schema | +| ---------------- | --------------- | ------ | +| RawTransaction\* | Raw transaction | string | + +### SendTransactionOutput + +#### Description + +Represents the output of sending a transaction. + +#### Schema + +| Name | Schema | +| --------------- | ------ | +| TransactionId\* | string | + +### SendTransactionsInput + +#### Description + +Represents the input parameters for sending multiple transactions. + +#### Schema + +| Name | Description | Schema | +| ----------------- | ---------------- | ------ | +| RawTransactions\* | Raw transactions | string | + +### TaskQueueInfoDto + +#### Description + +Represents information about a task queue. + +#### Schema + +| Name | Schema | +|--------- + +|-----------------| +| Count* | integer (int32) | +| Time* | string (date-time)| + +### Timestamp + +#### Description + +Represents a timestamp. + +#### Schema + +| Name | Schema | +| --------- | --------------- | +| Seconds\* | integer (int64) | +| Nanos\* | integer (int32) | + +### TransactionDto + +#### Description + +Represents a transaction. + +#### Schema + +| Name | Schema | +| ----------------- | ------------------ | +| Hash\* | string | +| Height\* | integer (int64) | +| MethodName\* | string | +| Params\* | string | +| Receiver\* | string | +| RefBlockNumber\* | integer (int64) | +| Sender\* | string | +| Time\* | string (date-time) | +| TransactionSize\* | integer (int32) | +| TxStatus\* | string | + +### TransactionResultDto + +#### Description + +Represents the result of a transaction. + +#### Schema + +| Name | Description | Schema | +| --------------- | ------------------------------ | ----------------------- | +| BlockHash | Block hash (optional) | string | +| BlockNumber | Block number (optional) | integer (int64) | +| Bloom | Bloom filter (optional) | string | +| Error | Error message (optional) | string | +| Logs | Logs (optional) | < `LogEventDto` > array | +| ReturnValue | Return value (optional) | string | +| Status | Transaction status (optional) | string | +| Transaction | Transaction details (optional) | `TransactionDto` | +| TransactionId | Transaction ID (optional) | string | +| TransactionSize | Transaction size (optional) | integer (int32) | + +### CalculateTransactionFeeInput + +#### Description + +Represents the input parameters for calculating transaction fees. + +#### Schema + +| Name | Description | Schema | +| -------------- | ------------------------------- | ------ | +| RawTransaction | Raw transaction data (optional) | string | + +### CalculateTransactionFeeOutput + +#### Description + +Represents the output of calculating transaction fees. + +#### Schema + +| Name | Description | Schema | +| -------------- | ---------------------------------- | ------------------------ | +| Success | Success flag (optional) | bool | +| TransactionFee | Transaction fee details (optional) | Dictionary`` | +| ResourceFee | Resource fee details (optional) | Dictionary` `| diff --git a/docs/Reference/command-line-Interface/Commands.md b/docs/References/command-line-Interface/Commands.md similarity index 100% rename from docs/Reference/command-line-Interface/Commands.md rename to docs/References/command-line-Interface/Commands.md diff --git a/docs/Reference/command-line-Interface/Introduction.md b/docs/References/command-line-Interface/Introduction.md similarity index 100% rename from docs/Reference/command-line-Interface/Introduction.md rename to docs/References/command-line-Interface/Introduction.md diff --git a/docs/Reference/command-line-Interface/_category_.json b/docs/References/command-line-Interface/_category_.json similarity index 100% rename from docs/Reference/command-line-Interface/_category_.json rename to docs/References/command-line-Interface/_category_.json diff --git a/docs/Resources/wallet-and-block-explorer b/docs/Resources/wallet-and-block-explorer.md similarity index 100% rename from docs/Resources/wallet-and-block-explorer rename to docs/Resources/wallet-and-block-explorer.md