diff --git a/docs/Developer Tools/Chain Sdk/csharp-sdk.md b/docs/Developer Tools/Chain Sdk/csharp-sdk.md deleted file mode 100644 index 1fbe765c..00000000 --- a/docs/Developer Tools/Chain Sdk/csharp-sdk.md +++ /dev/null @@ -1,812 +0,0 @@ ---- -sidebar_position: 2 -title: C# SDK -description: C# SDK -image: /img/Logo.aelf.svg ---- - -# 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 - - -```csharp -// Get token contract address. -var tokenContractAddress = await client.GetContractAddressByNameAsync(HashHelper.ComputeFrom("AElf.ContractNames.Token")); - -var methodName = "Transfer"; -var param = new TransferInput -{ - To = new Address {Value = Address.FromBase58("7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz").Value}, - Symbol = "ELF", - Amount = 1000000000, - Memo = "transfer in demo" -}; -var ownerAddress = client.GetAddressFromPrivateKey(PrivateKey); - -// Generate a transfer transaction. -var transaction = await client.GenerateTransaction(ownerAddress, tokenContractAddress.ToBase58(), methodName, param); -var txWithSign = client.SignTransaction(PrivateKey, transaction); - -// Send the transfer transaction to AElf chain node. -var result = await client.SendTransactionAsync(new SendTransactionInput -{ - RawTransaction = txWithSign.ToByteArray().ToHex() -}); - -await Task.Delay(4000); -// After the transaction is mined, query the execution results. -var transactionResult = await client.GetTransactionResultAsync(result.TransactionId); -Console.WriteLine(transactionResult.Status); - -// Query account balance. -var paramGetBalance = new GetBalanceInput -{ - Symbol = "ELF", - Owner = new Address {Value = Address.FromBase58(ownerAddress).Value} -}; -var transactionGetBalance =await client.GenerateTransaction(ownerAddress, tokenContractAddress.ToBase58(), "GetBalance", paramGetBalance); -var txWithSignGetBalance = client.SignTransaction(PrivateKey, transactionGetBalance); - -var transactionGetBalanceResult = await client.ExecuteTransactionAsync(new ExecuteTransactionDto -{ - RawTransaction = txWithSignGetBalance.ToByteArray().ToHex() -}); - -var balance = GetBalanceOutput.Parser.ParseFrom(ByteArrayHelper.HexstringToByteArray(transactionGetBalanceResult)); -Console.WriteLine(balance.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`. - -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 - -- **Web API path**: `/api/blockChain/chainStatus` - -- **Parameters** : None - -- **Returns**: `ChainStatusDto` - - ChainId - string - - Branches - Dictionary`` - - NotLinkedBlocks - Dictionary`` - - LongestChainHeight - long - - LongestChainHash - string - - GenesisBlockHash - string - - GenesisContractAddress - string - - LastIrreversibleBlockHash - string - - LastIrreversibleBlockHeight - long - - BestChainHash - string - - BestChainHeight - long - -#### Example: - -```csharp -await client.GetChainStatusAsync(); -``` - - -### 3. Get Contract File Descriptor Set - -- **Web API path**: `/api/blockChain/contractFileDescriptorSet` - -- **Parameters** : - - contractAddress - string - -- **Returns**: `[]byte` - - -#### Example: - -```csharp -await client.GetContractFileDescriptorSetAsync(address); -``` - - -### 4. Get Block Height - -- **Web API path**: `/api/blockChain/blockHeight` - -- **Parameters** : None - -- **Returns**: `long` - - -#### Example: - -```csharp -await client.GetBlockHeightAsync(); -``` - - -### 5. 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 - long - - Time - string - - ChainId - string - - Bloom - string - - SignerPubkey - string - - Body - BlockBodyDto - - TransactionsCount - int - - Transactions - []string - -#### Example: - -```csharp -await client.GetBlockByHashAsync(blockHash); -``` - - -### 6. Get Block Information by Block Height - -- **Web API path**: `/api/blockChain/blockByHeight` - -- **Parameters** : - - blockHeight - long - - includeTransactions - bool - -- **Returns**: `BlockDto` - - - BlockHash - string - - Header - BlockHeaderDto - - PreviousBlockHash - string - - MerkleTreeRootOfTransactions - string - - MerkleTreeRootOfWorldState - string - - Extra - string - - Height - long - - Time - string - - ChainId - string - - Bloom - string - - SignerPubkey - string - - Body - BlockBodyDto - - TransactionsCount - int - - Transactions - []string - - -#### Example: - -```csharp -await client.GetBlockByHeightAsync(height); -``` - - -### 7. Get Transaction Result - -- **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 - long - - BlockHash - string - - Transaction - TransactionDto - - From - string - - To - string - - RefBlockNumber - long - - RefBlockPrefix - string - - MethodName - string - - Params - string - - Signature - string - - Error - string - - -#### Example: - -```csharp -await client.GetTransactionResultAsync(transactionId); -``` - - -### 8. Get Multiple Transaction Results in a Block - -- **Web API path**: `/api/blockChain/transactionResults` - -- **Parameters** : - - blockHash - string - - offset - int - - limit - int - -- **Returns**: `List` - The array of transaction result: - - the transaction result object - - -#### Example: - -```csharp -await client.GetTransactionResultsAsync(blockHash, 0, 10); -``` - -### 9. Get Transaction Pool Status - -- **Web API path**: `/api/blockChain/transactionPoolStatus` - -- **Parameters** : None - -- **Returns**: `TransactionPoolStatusOutput` - - Queued - int - - Validated - int - - -#### Example: - -```csharp -var transactionPoolStatus = await client.GetTransactionPoolStatusAsync(); -``` - -### 10. Send Transaction - -- **Web API path**: `/api/blockChain/sendTransaction` (POST) - -- **Parameters** : - - `SendRawTransactionInput` - Serialization of data into protobuf data: - -`RawTransaction` - string - -- **Returns**: `SendRawTransactionOutput` - - TransactionId - string - - -#### Example: - -```csharp -var sendTransactionOutput = await client.SendTransactionAsync(sendTransactionInput); -``` - -### 11. Send Raw Transaction - -- **Web API path**: `/api/blockChain/sendTransaction` (POST) - -- **Parameters** : - - SendRawTransactionInput - Serialization of data into protobuf data: - - `Transaction` - string - - `Signature` - string - - `ReturnTransaction` - bool - -- **Returns**: `SendRawTransactionOutput` - - TransactionId - string - - Transaction - TransactionDto - - -#### Example: - -```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 - -- **Web API path**: `/api/blockChain/sendTransactions` (POST) - -- **Parameters** : - - `SendTransactionsInput` - Serialization of data into protobuf data: - - `SendTransactionsInput` - string - -- **Returns**: `string[]` - - -#### Example: - -```csharp -await client.SendTransactionsAsync(input); -``` - -### 13. Create Raw Transaction - -- **Web API path**: `/api/blockChain/rawTransaction` (POST) - -- **Parameters** : - - `CreateRawTransactionInput` - - `From` - string - - `To` - string - - `RefBlockNumber` - long - - `RefBlockHash` - string - - `MethodName` - string - - `Params` - string - -- **Returns**: - - `CreateRawTransactionOutput` - - `RawTransactions` - string - - -#### Example: - -```csharp -await client.CreateRawTransactionAsync(input); -``` - -### 14. Execute Transaction - -- **Web API path**: `/api/blockChain/executeTransaction` (POST) - -- **Parameters** : - - `ExecuteRawTransactionDto` - Serialization of data into protobuf data: - - `RawTransaction` - string - -- **Returns**: `string` - - -#### Example: - -```csharp -await client.ExecuteRawTransactionAsync(input); -``` - -### 15. Execute Raw Transaction - -- **Web API path**: `/api/blockChain/executeRawTransaction` (POST) - -- **Parameters** : - - `ExecuteRawTransactionDto` - Serialization of data into protobuf data: - - `RawTransaction` - string - - `Signature` - string - -- **Returns**: `string` - - -#### Example: -```csharp -await client.ExecuteRawTransactionAsync(input); -``` - - -### 16. Get Peers - -- **Web API path**: `/api/net/peers` - -- **Parameters** : - - `withMetrics` - bool - -- **Returns**: `List` - - - `IpAddress` - string - - `ProtocolVersion` - int - - `ConnectionTime` - long - - `ConnectionStatus` - string - - `Inbound` - bool - - `BufferedTransactionsCount` - int - - `BufferedBlocksCount` - int - - `BufferedAnnouncementsCount` - int - - `NodeVersion` - string - - `RequestMetrics` - List`` - - `RoundTripTime` - long - - `MethodName` - string - - `Info` - string - - `RequestTime` - string - - - -#### Example: - -```csharp -await client.GetPeersAsync(false); -``` - - -### 17. Add Peer - -Attempts to remove a node from the connected network nodes. - -- **Web API path**: `/api/net/peer` (POST) - -- **Parameters** : - - `ipAddress` - string - -- **Returns**: `bool` - -#### Example: - -```csharp -await client.AddPeerAsync("127.0.0.1:7001"); -``` - - -### 18. Remove Peer - -Attempts to remove a node from the connected network nodes. - -- **Web API path**: `/api/net/peer` (DELETE) - -- **Parameters** : - - `ipAddress` - string - -- **Returns**: `bool` - -```csharp -await client.RemovePeerAsync("127.0.0.1:7001"); -``` - - -### 19. Calculate Transaction Fee - -- **Web API path**: `/api/blockChain/calculateTransactionFee` (POST) - -- **Parameters** : - - `CalculateTransactionFeeInput` - The object with the following structure : - - `RawTrasaction` - string - -- **Returns**: - - `TransactionFeeResultOutput` - - `Success` - bool - - `TransactionFee` - map[string]interface{} - - `ResourceFee` - map[string]interface{} - -#### Example: - -```csharp -var input = new CalculateTransactionFeeInput{ - RawTransaction = RawTransaction -}; -await Client.CalculateTransactionFeeAsync(input); -``` - - -### 20. Get Network Information - -- **Web API path**: `/api/net/networkInfo` - -- **Parameters** : Empty - -- **Returns**: - - `NetworkInfoOutput` - - `Version` - string - - `ProtocolVersion` - int - - `Connections` - int - -#### Example: - -```csharp -await client.GetNetworkInfoAsync(); -``` - -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. - -- **Parameters**: None - -- **Returns** : - - `bool`: Connection status - -#### Example: - -```csharp -bool isConnected = await client.IsConnectedAsync(); -Console.WriteLine($"Is Connected: {isConnected}"); -``` - -### 2. GetGenesisContractAddress - -Get the address of the genesis contract. - -- **Parameters**: None - -- **Returns** : - - `string`: Genesis contract address - -#### Example: - -```csharp -await client.GetGenesisContractAddressAsync(); -``` - -### 3. GetContractAddressByName - -Get the address of a contract by the given contract name hash. - -- **Parameters**: - - `contractNameHash` (string): Hash of the contract name - -- **Returns** : - - `string`: Contract address - -#### Example: - -```csharp -await client.GetContractAddressByNameAsync(contractNameHash); -``` - -### 4. GenerateTransaction - -Build a transaction from the input parameters. - -- **Parameters**: - - `from` (string): Sender's address - - `to` (string): Recipient's address - - `methodName` (string): Method name - - `input` IMessage - -- **Returns** : - - `Transaction`: Built transaction - -#### Example: - -```csharp -await client.GenerateTransactionAsync(from, to, methodName, input); -``` - -### 5. GetFormattedAddress - -Convert the `Address` to the displayed string format: symbol_base58-string_base58-string_chain-id. - -- **Parameters**: - - `address` (string): Address to format - -- **Returns** : - - `string`: Formatted address - -#### Example: - -```csharp -await client.GetFormattedAddressAsync(address); -``` - -### 6. SignTransaction - -- **Parameters**: - - `privateKey` (string): Address to format - - `transaction` (string): Address to format - -- **Returns** : - - `Transaction` - -#### Example: - -```csharp -client.SignTransaction(privateKeyHex, transaction); -``` - -### 7. GetAddressFromPubKey - -Get the account address through the public key. - -- **Parameters**: - - `pubKey` (string): Public key - -- **Returns** : - - `string`: Account address - -#### Example: - -```csharp -client.GetAddressFromPubKey(pubKey); -``` - -### 8. GetAddressFromPrivateKey - -Get the account address through the private key. - -- **Parameters**: - - `privateKey` (string): Private key - -- **Returns** : - - `string`: Account address - -#### Example: - -```csharp -client.GetAddressFromPrivateKey(privateKeyHex); -``` - -### 9. GenerateKeyPairInfo - -Generate a new account key pair. - -- **Parameters**: None - -- **Returns** : - - `KeyPairInfo` - - `PrivateKey` - string - - `PublicKey` - string - - `Address` - string - -#### Example: - -```csharp -client.GenerateKeyPairInfo(); -``` - -## 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 deleted file mode 100644 index c48bc49f..00000000 --- a/docs/Developer Tools/Chain Sdk/go-sdk.md +++ /dev/null @@ -1,740 +0,0 @@ ---- -sidebar_position: 3 -title: Go SDK -description: Go SDK -image: /img/Logo.aelf.svg ---- - -# 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") - -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: - - -```go -// Get token contract address. -tokenContractAddress, _ := aelf.GetContractAddressByName("AElf.ContractNames.Token") -fromAddress := aelf.GetAddressFromPrivateKey(aelf.PrivateKey) -methodName := "Transfer" -toAddress, _ := util.Base58StringToAddress("7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz") - -params := &pb.TransferInput{ - To: toAddress, - Symbol: "ELF", - Amount: 1000000000, - Memo: "transfer in demo", -} -paramsByte, _ := proto.Marshal(params) - -// Generate a transfer transaction. -transaction, _ := aelf.CreateTransaction(fromAddress, tokenContractAddress, methodName, paramsByte) -signature, _ := aelf.SignTransaction(aelf.PrivateKey, transaction) -transaction.Signature = signature - -// Send the transfer transaction to AElf chain node. -transactionByets, _ := proto.Marshal(transaction) -sendResult, _ := aelf.SendTransaction(hex.EncodeToString(transactionByets)) - -time.Sleep(time.Duration(4) * time.Second) -transactionResult, _ := aelf.GetTransactionResult(sendResult.TransactionID) -fmt.Println(transactionResult) - -// Query account balance. -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 - -getBalanceTransactionByets, _ := proto.Marshal(getBalanceTransaction) -getBalanceResult, _ := aelf.ExecuteTransaction(hex.EncodeToString(getBalanceTransactionByets)) -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` - Serialization of data into protobuf data: - - `RawTransaction` - string - -- **Returns**: - - - `SendTransactionOutput` - - `TransactionId` - string - - -#### Example: - -```go -sendResult, err := aelf.SendTransaction(input) -``` - -### SendRawTransaction - -- **Web API path**: `/api/blockChain/sendTransaction` (POST) - -- **Parameters** : - - `SendRawTransactionInput` - Serialization of data into protobuf data: - - `RawTransaction` - string - - `Signature` - string - - `ReturnTransaction` - 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 - - Serialization of data into protobuf data: - -- **Returns**: `[]interface{}` - - -#### Example: - -```go -results, err := aelf.SendTransactions(transactions) -``` - - -### CreateRawTransaction - -Creates an unsigned serialized transaction. - - -- **Web API path**: `/api/blockChain/rawTransaction` (POST) - -- **Parameters** : - - - `CreateRawTransactionInput` - - `From` - string - - `To` - string - - `RefBlockNumber` - long - - `RefBlockHash` - string - - `MethodName` - string - - `Params` - string - -- **Returns**: - - - `CreateRawTransactionOutput` - - `RawTransactions` - string - - -#### 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` - Serialization of data into protobuf data: - - `RawTransaction` - string - - `Signature` - 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` - The object with the following structure : - - `RawTrasaction` - 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` - - `PrivateKey` - - `PublicKey` - - `Address` - -#### Example: - -```go -keyPair := aelf.GenerateKeyPairInfo() -``` - - -## Supported Go Version - -- Go 1.13 diff --git a/docs/Developer Tools/Chain Sdk/index.md b/docs/Developer Tools/Chain Sdk/index.md deleted file mode 100644 index 09772988..00000000 --- a/docs/Developer Tools/Chain Sdk/index.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -sidebar_position: 2 -title: Chain SDK -description: Chain SDK -image: /img/Logo.aelf.svg ---- \ No newline at end of file diff --git a/docs/Developer Tools/Chain Sdk/java-sdk.md b/docs/Developer Tools/Chain Sdk/java-sdk.md deleted file mode 100644 index 54d23248..00000000 --- a/docs/Developer Tools/Chain Sdk/java-sdk.md +++ /dev/null @@ -1,779 +0,0 @@ ---- -sidebar_position: 4 -title: JAVA SDK -description: JAVA SDK -image: /img/Logo.aelf.svg ---- - -# 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 - - -```java -// Get token contract address. -String tokenContractAddress = client.getContractAddressByName(privateKey, Sha256.getBytesSha256("AElf.ContractNames.Token")); - -Client.Address.Builder to = Client.Address.newBuilder(); -to.setValue(ByteString.copyFrom(Base58.decodeChecked("7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz"))); -Client.Address toObj = to.build(); - -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(); - -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(); - -// Send the transfer transaction to AElf chain node. -SendTransactionInput sendTransactionInputObj = new SendTransactionInput(); -sendTransactionInputObj.setRawTransaction(Hex.toHexString(transactionTransferObj.toByteArray())); -SendTransactionOutput sendResult = client.sendTransaction(sendTransactionInputObj); - -Thread.sleep(4000); -// After the transaction is mined, query the execution results. -TransactionResultDto transactionResult = client.getTransactionResult(sendResult.getTransactionId()); -System.out.println(transactionResult.getStatus()); - -// Query account balance. -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` - - `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` - - `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 deleted file mode 100644 index 3e0cd155..00000000 --- a/docs/Developer Tools/Chain Sdk/javascript-sdk.md +++ /dev/null @@ -1,683 +0,0 @@ ---- -sidebar_position: 1 -title: Javascript SDK -description: Javascript SDK -image: /img/Logo.aelf.svg ---- - -# 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`. - -parameters and returns based on the URL: [https://aelf-public-node.aelf.io/swagger/index.html](https://aelf-public-node.aelf.io/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` - - - `ChainId` - String - - `Branches` - Object - - `NotLinkedBlocks` - Object - - `LongestChainHeight` - Number - - `LongestChainHash` - String - - `GenesisBlockHash` - String - - `GenesisContractAddress` - String - - `LastIrreversibleBlockHash` - String - - `LastIrreversibleBlockHeight` - Number - - `BestChainHash` - String - - `BestChainHeight` - Number - - -#### 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**: - - **`blockHash`** (String) - - **`includeTransactions`** (Boolean) - - `true` require transaction ids list in the block - - `false` Doesn’t require transaction ids list in the block - -- **Returns**: `Object` - - - `BlockHash` - String - - - `Header` - Object - - `PreviousBlockHash` - String - - `MerkleTreeRootOfTransactions` - String - - `MerkleTreeRootOfWorldState` - String - - `Extra` - Array - - `Height` - Number - - `Time` - google.protobuf.Timestamp - - `ChainId` - String - - `Bloom` - String - - `SignerPubkey` - String - - - `Body` - Object - - `TransactionsCount` - Number - - `Transactions` - Array - - `transactionId` - String - - -#### 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) - - `true` require transaction ids list in the block - - `false` Doesn’t require transaction ids list in the block - -- **Returns**: `Object` - - - `BlockHash` - String - - - `Header` - Object - - `PreviousBlockHash` - String - - `MerkleTreeRootOfTransactions` - String - - `MerkleTreeRootOfWorldState` - String - - `Extra` - Array - - `Height` - Number - - `Time` - google.protobuf.Timestamp - - `ChainId` - String - - `Bloom` - String - - `SignerPubkey` - String - - - `Body` - Object - - `TransactionsCount` - Number - - `Transactions` - Array - - `transactionId` - String - - - -#### 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` - - - `TransactionId` - String - - `Status` - String - - `Logs` - Array - - `Address` - String - - `Name` - String - - `Indexed` - Array - - `NonIndexed` - Number - - `Bloom` - String - - `BlockNumber` - Number - - `Transaction` - Object - - `From` - String - - `To` - String - - `RefBlockNumber` - Number - - `RefBlockPrefix` - String - - `MethodName` - String - - `Params` - Object - - `Signature` - String - - `ReadableReturnValue` - Object - - `Error` - String - - -#### 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` - The array of method descriptions: - - the transaction result object - - -#### 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 - - -### 9. Send Transaction - - -- **Web API Path**: `/api/blockChain/sendTransaction` -- **Method**: POST -- **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) - - `RawTransaction` - String - - -### 10. Send Multiple Transactions - -- **Web API Path**: `/api/blockChain/sendTransactions` -- **Method**: POST -- **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) - - `RawTransaction` - String - - -### 11. Call Read-Only Method - -Call a read-only method on a contract. - -- **Method**: POST -- **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) - - `RawTransaction` - String -- **Returns**: Method call result - - -### 12. Get Peers - -Get peer info about the connected network nodes. - -- **Method**: GET -- **Parameters**: `withMetrics` (Boolean) - - `true` with metrics - - `false` without metrics - - -### 13. Add Peer - -Attempts to add a node to the connected network nodes - -- **Method**: POST -- **Parameters**: `Object` The object with the following structure : - - `Address` - String - -### 14. Remove Peer - -Attempts to remove a node from the connected network nodes - -- **Method**: DELETE -- **Parameters**: `address` (String) - - -### 15. Calculate Transaction Fee - - -- **Web API Path**: `/api/blockChain/calculateTransactionFee` -- **Method**: POST -- **Parameters**: `CalculateTransactionFeeInput` (Object with RawTransaction string): - - `RawTransaction` - String -- **Returns**: `CalculateTransactionFeeOutput` (Object with fee details): - - `Success` - Bool - - `TransactionFee` - Array - - `ResourceFee` - Array - - -#### Example - -```javascript -aelf.chain.calculateTransactionFee(rawTransaction) - .then(res => { - console.log(res); - }); -``` - -### 16. Network Info - - -- **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 deleted file mode 100644 index 3bf88153..00000000 --- a/docs/Developer Tools/Chain Sdk/php-skd.md +++ /dev/null @@ -1,786 +0,0 @@ ---- -sidebar_position: 5 -title: PHP SDK -description: PHP SDK -image: /img/Logo.aelf.svg ---- - -# 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; -// create a new instance of AElf -$url = '127.0.0.1:8000'; -$aelf = new AElf($url); -``` - - -### 1. Get Chain Status - -- **API Path**: `/api/blockChain/chainStatus` - -- **Parameters**: None - -- **Returns**: - - - `Array` - - `ChainId` - String - - `Branches` - Array - - `NotLinkedBlocks` - Array - - `LongestChainHeight` - Integer - - `LongestChainHash` - String - - `GenesisBlockHash` - String - - `GenesisContractAddress` - String - - `LastIrreversibleBlockHash` - String - - `LastIrreversibleBlockHeight` - Integer - - `BestChainHash` - String - - `BestChainHeight` - Integer - - -- **Example** : - -```php -// create a new instance of AElf -$aelf = new AElf($url); - -$chainStatus = $aelf->getChainStatus(); -print_r($chainStatus); -``` - - - -### 2. Get Block Height - -- **API Path**: `/api/blockChain/blockHeight` - -- **Parameters**: None - -- **Returns**: Integer - -- **Example** : - -```php -$aelf = new AElf($url); - -$height = $aelf->getBlockHeight(); -print($height); -``` - - -### 3. getBlock - -- **API Path**: `/api/blockChain/block` - -- **Parameters**: - - - `block_hash` (String) - - `include_transactions` (Boolean) - -- **Returns**: - - - `Array` - - `BlockHash` - String - - `Header` - Array - - `PreviousBlockHash` - String - - `MerkleTreeRootOfTransactions` - String - - `MerkleTreeRootOfWorldState` - String - - `Extra` - List - - `Height` - Integer - - `Time` - String - - `ChainId` - String - - `Bloom` - String - - `SignerPubkey` - String - - `Body` - Array - - `TransactionsCount` - Integer - - `Transactions` - Array - - `transactionId` - String - -- **Example** : - -```php -$aelf = new AElf($url); - -$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` - - `BlockHash` - String - - `Header` - Array - - `PreviousBlockHash` - String - - `MerkleTreeRootOfTransactions` - String - - `MerkleTreeRootOfWorldState` - String - - `Extra` - List - - `Height` - Integer - - `Time` - String - - `ChainId` - String - - `Bloom` - String - - `SignerPubkey` - String - - `Body` - Array - - `TransactionsCount` - Integer - - `Transactions` - Array - - `transactionId` - String - - -- **Example** : - -```php -$aelf = new AElf($url); - -$block = $aelf->getBlockByHeight(1, true); -print_r($block); -``` - - -### 5. Get Transaction Result - -- **API Path**: `/api/blockChain/transactionResult` - -- **Parameters**: - - - `transactionId` (String) - -- **Returns**: - - - `Object` - - `TransactionId` - String - - `Status` - String - - `Logs` - Array - - `Address` - String - - `Name` - String - - `Indexed` - Array - - `NonIndexed` - String - - `Bloom` - String - - `BlockNumber` - Integer - - `Transaction` - Array - - `From` - String - - `To` - String - - `RefBlockNumber` - Integer - - `RefBlockPrefix` - String - - `MethodName` - String - - `Params` - json - - `Signature` - String - - `transactionId` - String - - `ReadableReturnValue` - String - - `Error` - String - -- **Example** : - -```php -$aelf = new AElf($url); - -$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` - The array of method descriptions: - - the transaction result object - -- **Example** : - -```php -$aelf = new AElf($url); - -$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 -$aelf = new AElf($url); - -$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 -$aelf = new AElf($url); - -$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` - - `RawTransaction` - hex string bytes generated by transaction information - -- **Example** : - -```php -$aelf = new AElf($url); - -$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 -$aelf = new AElf($url); - -$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 -$aelf = new AElf($url); - -$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 -$aelf = new AElf($url); - -$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)` - - - `Success` - bool - - `TransactionFee` - Array - - `ResourceFee` - Array - -- **Example** : - -```php -$aelf = new AElf($url); - -$calculateTransactionFeeInputParam = [ - "rawTransaction" => $rawTransactionInput, -]; -$result = $aelf->calculateTransactionFee($calculateTransactionFeeInputParam); -print_r($result); -``` - - -### 18. Get Network Info - -- **API Path**: `/api/net/networkInfo` - -- **Example** : - -```php -$aelf = new AElf($url); - -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 deleted file mode 100644 index 004196d6..00000000 --- a/docs/Developer Tools/Chain Sdk/python-sdk.md +++ /dev/null @@ -1,851 +0,0 @@ ---- -sidebar_position: 6 -title: Python SDK -description: Python SDK -image: /img/Logo.aelf.svg ---- - -# 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/command-line-Interface/_category_.json b/docs/References/command-line-Interface/_category_.json deleted file mode 100644 index dfbb298a..00000000 --- a/docs/References/command-line-Interface/_category_.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "position": 1, - "label": "Command-line Interface" -} diff --git a/docs/References/command-line-Interface/index.md b/docs/References/command-line-Interface/index.md new file mode 100644 index 00000000..94ad8b9d --- /dev/null +++ b/docs/References/command-line-Interface/index.md @@ -0,0 +1,6 @@ +--- +sidebar_position: 2 +title: Command-line Interface +description: Command-line Interface +image: /img/Logo.aelf.svg +--- diff --git a/docs/Tools/Chain SDK/C# SDK/index.md b/docs/Tools/Chain SDK/C# SDK/index.md index ef06ba0f..1fbe765c 100644 --- a/docs/Tools/Chain SDK/C# SDK/index.md +++ b/docs/Tools/Chain SDK/C# SDK/index.md @@ -2,6 +2,7 @@ sidebar_position: 2 title: C# SDK description: C# SDK +image: /img/Logo.aelf.svg --- # aelf-sdk.cs - aelf C# API @@ -76,7 +77,54 @@ Console.WriteLine($"Connected: {isConnected}"); ### 3. Initiate a Transfer Transaction -#### a. Get Token Contract Address +```csharp +// Get token contract address. +var tokenContractAddress = await client.GetContractAddressByNameAsync(HashHelper.ComputeFrom("AElf.ContractNames.Token")); + +var methodName = "Transfer"; +var param = new TransferInput +{ + To = new Address {Value = Address.FromBase58("7s4XoUHfPuqoZAwnTV7pHWZAaivMiL8aZrDSnY9brE1woa8vz").Value}, + Symbol = "ELF", + Amount = 1000000000, + Memo = "transfer in demo" +}; +var ownerAddress = client.GetAddressFromPrivateKey(PrivateKey); + +// Generate a transfer transaction. +var transaction = await client.GenerateTransaction(ownerAddress, tokenContractAddress.ToBase58(), methodName, param); +var txWithSign = client.SignTransaction(PrivateKey, transaction); + +// Send the transfer transaction to AElf chain node. +var result = await client.SendTransactionAsync(new SendTransactionInput +{ + RawTransaction = txWithSign.ToByteArray().ToHex() +}); + +await Task.Delay(4000); +// After the transaction is mined, query the execution results. +var transactionResult = await client.GetTransactionResultAsync(result.TransactionId); +Console.WriteLine(transactionResult.Status); + +// Query account balance. +var paramGetBalance = new GetBalanceInput +{ + Symbol = "ELF", + Owner = new Address {Value = Address.FromBase58(ownerAddress).Value} +}; +var transactionGetBalance =await client.GenerateTransaction(ownerAddress, tokenContractAddress.ToBase58(), "GetBalance", paramGetBalance); +var txWithSignGetBalance = client.SignTransaction(PrivateKey, transactionGetBalance); + +var transactionGetBalanceResult = await client.ExecuteTransactionAsync(new ExecuteTransactionDto +{ + RawTransaction = txWithSignGetBalance.ToByteArray().ToHex() +}); + +var balance = GetBalanceOutput.Parser.ParseFrom(ByteArrayHelper.HexstringToByteArray(transactionGetBalanceResult)); +Console.WriteLine(balance.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`. + Here are the examples and code snippets for interacting with the AElf Web API using the `AElfClient` instance. ### 1. Create Instance @@ -179,111 +229,235 @@ AElfClient client = new AElfClient("http://127.0.0.1:1235"); ### 2. Get Chain Status -Get the current status of the blockchain. +- **Web API path**: `/api/blockChain/chainStatus` + +- **Parameters** : None + +- **Returns**: `ChainStatusDto` + - ChainId - string + - Branches - Dictionary`` + - NotLinkedBlocks - Dictionary`` + - LongestChainHeight - long + - LongestChainHash - string + - GenesisBlockHash - string + - GenesisContractAddress - string + - LastIrreversibleBlockHash - string + - LastIrreversibleBlockHeight - long + - BestChainHash - string + - BestChainHeight - long + +#### Example: ```csharp -var chainStatus = await client.GetChainStatusAsync(); -Console.WriteLine($"Chain ID: {chainStatus.ChainId}"); -Console.WriteLine($"Best Chain Height: {chainStatus.BestChainHeight}"); +await client.GetChainStatusAsync(); ``` ### 3. Get Contract File Descriptor Set -Get the protobuf definitions related to a contract. +- **Web API path**: `/api/blockChain/contractFileDescriptorSet` + +- **Parameters** : + - contractAddress - string + +- **Returns**: `[]byte` + + +#### Example: ```csharp -string contractAddress = "YOUR_CONTRACT_ADDRESS"; -var fileDescriptorSet = await client.GetContractFileDescriptorSetAsync(contractAddress); -Console.WriteLine($"File Descriptor Set: {fileDescriptorSet.Length} bytes"); +await client.GetContractFileDescriptorSetAsync(address); ``` ### 4. Get Block Height -Get the current best height of the chain. +- **Web API path**: `/api/blockChain/blockHeight` + +- **Parameters** : None + +- **Returns**: `long` + + +#### Example: ```csharp -var blockHeight = await client.GetBlockHeightAsync(); -Console.WriteLine($"Block Height: {blockHeight}"); +await client.GetBlockHeightAsync(); ``` ### 5. Get Block Information by Block Hash -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 - long + - Time - string + - ChainId - string + - Bloom - string + - SignerPubkey - string + - Body - BlockBodyDto + - TransactionsCount - int + - Transactions - []string + +#### Example: ```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}"); +await client.GetBlockByHashAsync(blockHash); ``` ### 6. Get Block Information by Block Height -Get block information by block height. +- **Web API path**: `/api/blockChain/blockByHeight` + +- **Parameters** : + - blockHeight - long + - includeTransactions - bool + +- **Returns**: `BlockDto` + + - BlockHash - string + - Header - BlockHeaderDto + - PreviousBlockHash - string + - MerkleTreeRootOfTransactions - string + - MerkleTreeRootOfWorldState - string + - Extra - string + - Height - long + - Time - string + - ChainId - string + - Bloom - string + - SignerPubkey - string + - Body - BlockBodyDto + - TransactionsCount - int + - Transactions - []string + + +#### Example: ```csharp -long height = 100; -var blockByHeight = await client.GetBlockByHeightAsync(height); -Console.WriteLine($"Block Hash: {blockByHeight.BlockHash}"); -Console.WriteLine($"Block Height: {blockByHeight.Header.Height}"); +await client.GetBlockByHeightAsync(height); ``` ### 7. Get Transaction Result -Get the result of a transaction. +- **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 - long + - BlockHash - string + - Transaction - TransactionDto + - From - string + - To - string + - RefBlockNumber - long + - RefBlockPrefix - string + - MethodName - string + - Params - string + - Signature - string + - Error - string + + +#### Example: ```csharp -string transactionId = "YOUR_TRANSACTION_ID"; -var transactionResult = await client.GetTransactionResultAsync(transactionId); -Console.WriteLine($"Transaction Status: {transactionResult.Status}"); -Console.WriteLine($"Block Number: {transactionResult.BlockNumber}"); +await client.GetTransactionResultAsync(transactionId); ``` ### 8. Get Multiple Transaction Results in a Block -Get multiple transaction results in a block. +- **Web API path**: `/api/blockChain/transactionResults` + +- **Parameters** : + - blockHash - string + - offset - int + - limit - int + +- **Returns**: `List` - The array of transaction result: + - the transaction result object + + +#### Example: ```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}"); -} +await client.GetTransactionResultsAsync(blockHash, 0, 10); ``` ### 9. Get Transaction Pool Status -Get the transaction pool status. +- **Web API path**: `/api/blockChain/transactionPoolStatus` + +- **Parameters** : None + +- **Returns**: `TransactionPoolStatusOutput` + - Queued - int + - Validated - int + + +#### Example: ```csharp var transactionPoolStatus = await client.GetTransactionPoolStatusAsync(); -Console.WriteLine($"Queued Transactions: {transactionPoolStatus.Queued}"); -Console.WriteLine($"Validated Transactions: {transactionPoolStatus.Validated}"); ``` ### 10. Send Transaction -Broadcast a transaction. +- **Web API path**: `/api/blockChain/sendTransaction` (POST) + +- **Parameters** : + - `SendRawTransactionInput` - Serialization of data into protobuf data: + -`RawTransaction` - string + +- **Returns**: `SendRawTransactionOutput` + - TransactionId - string + + +#### Example: ```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. +- **Web API path**: `/api/blockChain/sendTransaction` (POST) + +- **Parameters** : + - SendRawTransactionInput - Serialization of data into protobuf data: + - `Transaction` - string + - `Signature` - string + - `ReturnTransaction` - bool + +- **Returns**: `SendRawTransactionOutput` + - TransactionId - string + - Transaction - TransactionDto + + +#### Example: ```csharp var sendRawTransactionInput = new SendRawTransactionInput @@ -298,87 +472,128 @@ Console.WriteLine($"Transaction ID: {sendRawTransactionOutput.TransactionId}"); ### 12. Send Multiple Transactions -Broadcast multiple transactions. +- **Web API path**: `/api/blockChain/sendTransactions` (POST) + +- **Parameters** : + - `SendTransactionsInput` - Serialization of data into protobuf data: + - `SendTransactionsInput` - string + +- **Returns**: `string[]` + + +#### Example: ```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}"); -} +await client.SendTransactionsAsync(input); ``` ### 13. Create Raw Transaction -Creates an unsigned serialized transaction. +- **Web API path**: `/api/blockChain/rawTransaction` (POST) + +- **Parameters** : + - `CreateRawTransactionInput` + - `From` - string + - `To` - string + - `RefBlockNumber` - long + - `RefBlockHash` - string + - `MethodName` - string + - `Params` - string + +- **Returns**: + - `CreateRawTransactionOutput` + - `RawTransactions` - string + + +#### Example: ```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}"); +await client.CreateRawTransactionAsync(input); ``` ### 14. Execute Transaction -Call a read-only method on a contract. +- **Web API path**: `/api/blockChain/executeTransaction` (POST) + +- **Parameters** : + - `ExecuteRawTransactionDto` - Serialization of data into protobuf data: + - `RawTransaction` - string + +- **Returns**: `string` + + +#### Example: ```csharp -var executeTransactionDto = new ExecuteTransactionDto -{ - RawTransaction = "YOUR_RAW_TRANSACTION" -}; -var executionResult = await client.ExecuteTransactionAsync(executeTransactionDto); -Console.WriteLine($"Execution Result: {executionResult}"); +await client.ExecuteRawTransactionAsync(input); ``` ### 15. Execute Raw Transaction -Call a read-only method on a contract with a raw transaction. +- **Web API path**: `/api/blockChain/executeRawTransaction` (POST) +- **Parameters** : + - `ExecuteRawTransactionDto` - Serialization of data into protobuf data: + - `RawTransaction` - string + - `Signature` - string + +- **Returns**: `string` + + +#### Example: ```csharp -var executeRawTransactionDto = new ExecuteRawTransactionDto -{ - RawTransaction = "YOUR_RAW_TRANSACTION", - Signature = "YOUR_SIGNATURE" -}; -var executeRawResult = await client.ExecuteRawTransactionAsync(executeRawTransactionDto); -Console.WriteLine($"Execution Result: {executeRawResult}"); +await client.ExecuteRawTransactionAsync(input); ``` ### 16. Get Peers -Get peer info about the connected network nodes. +- **Web API path**: `/api/net/peers` + +- **Parameters** : + - `withMetrics` - bool + +- **Returns**: `List` + + - `IpAddress` - string + - `ProtocolVersion` - int + - `ConnectionTime` - long + - `ConnectionStatus` - string + - `Inbound` - bool + - `BufferedTransactionsCount` - int + - `BufferedBlocksCount` - int + - `BufferedAnnouncementsCount` - int + - `NodeVersion` - string + - `RequestMetrics` - List`` + - `RoundTripTime` - long + - `MethodName` - string + - `Info` - string + - `RequestTime` - string + + + +#### Example: ```csharp -var peers = await client.GetPeersAsync(false); -foreach (var peer in peers) -{ - Console.WriteLine($"Peer IP: {peer.IpAddress}, Connection Status: {peer.ConnectionStatus}"); -} +await client.GetPeersAsync(false); ``` ### 17. Add Peer -Attempts to add a node to the connected network nodes. +Attempts to remove a node from the connected network nodes. + +- **Web API path**: `/api/net/peer` (POST) + +- **Parameters** : + - `ipAddress` - string +- **Returns**: `bool` + +#### Example: ```csharp -var isPeerAdded = await client.AddPeerAsync("127.0.0.1:7001"); -Console.WriteLine($"Peer Added: {isPeerAdded}"); +await client.AddPeerAsync("127.0.0.1:7001"); ``` @@ -386,33 +601,61 @@ Console.WriteLine($"Peer Added: {isPeerAdded}"); Attempts to remove a node from the connected network nodes. +- **Web API path**: `/api/net/peer` (DELETE) + +- **Parameters** : + - `ipAddress` - string + +- **Returns**: `bool` + ```csharp -var isPeerRemoved = await client.RemovePeerAsync("127.0.0.1:7001"); -Console.WriteLine($"Peer Removed: {isPeerRemoved}"); +await client.RemovePeerAsync("127.0.0.1:7001"); ``` ### 19. Calculate Transaction Fee +- **Web API path**: `/api/blockChain/calculateTransactionFee` (POST) + +- **Parameters** : + - `CalculateTransactionFeeInput` - The object with the following structure : + - `RawTrasaction` - string + +- **Returns**: + - `TransactionFeeResultOutput` + - `Success` - bool + - `TransactionFee` - map[string]interface{} + - `ResourceFee` - map[string]interface{} + +#### Example: + ```csharp -var calculateTransactionFeeInput = new CalculateTransactionFeeInput -{ - RawTransaction = "YOUR_RAW_TRANSACTION" +var input = new CalculateTransactionFeeInput{ + RawTransaction = RawTransaction }; -var transactionFeeResult = await client.CalculateTransactionFeeAsync(calculateTransactionFeeInput); -Console.WriteLine($"Transaction Fee: {transactionFeeResult.TransactionFee}"); +await Client.CalculateTransactionFeeAsync(input); ``` ### 20. Get Network Information +- **Web API path**: `/api/net/networkInfo` + +- **Parameters** : Empty + +- **Returns**: + - `NetworkInfoOutput` + - `Version` - string + - `ProtocolVersion` - int + - `Connections` - int + +#### Example: + ```csharp -var networkInfo = await client.GetNetworkInfoAsync(); -Console.WriteLine($"Network Version: {networkInfo.Version}"); -Console.WriteLine($"Connections: {networkInfo.Connections}"); +await client.GetNetworkInfoAsync(); ``` -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. +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 @@ -421,6 +664,13 @@ These examples demonstrate how to use the AElf Web API in C# using the `AElfClie Verify whether this SDK successfully connects to the chain. +- **Parameters**: None + +- **Returns** : + - `bool`: Connection status + +#### Example: + ```csharp bool isConnected = await client.IsConnectedAsync(); Console.WriteLine($"Is Connected: {isConnected}"); @@ -430,92 +680,131 @@ Console.WriteLine($"Is Connected: {isConnected}"); Get the address of the genesis contract. +- **Parameters**: None + +- **Returns** : + - `string`: Genesis contract address + +#### Example: ```csharp -string genesisContractAddress = await client.GetGenesisContractAddressAsync(); -Console.WriteLine($"Genesis Contract Address: {genesisContractAddress}"); +await client.GetGenesisContractAddressAsync(); ``` ### 3. GetContractAddressByName Get the address of a contract by the given contract name hash. +- **Parameters**: + - `contractNameHash` (string): Hash of the contract name + +- **Returns** : + - `string`: Contract address + +#### Example: ```csharp -var contractNameHash = HashHelper.ComputeFrom("AElf.ContractNames.Token"); -string contractAddress = await client.GetContractAddressByNameAsync(contractNameHash); -Console.WriteLine($"Contract Address: {contractAddress}"); +await client.GetContractAddressByNameAsync(contractNameHash); ``` ### 4. GenerateTransaction Build a transaction from the input parameters. +- **Parameters**: + - `from` (string): Sender's address + - `to` (string): Recipient's address + - `methodName` (string): Method name + - `input` IMessage -```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" -}; +- **Returns** : + - `Transaction`: Built transaction + +#### Example: -Transaction transaction = await client.GenerateTransactionAsync(from, to, methodName, input); -Console.WriteLine($"Transaction: {transaction}"); +```csharp +await client.GenerateTransactionAsync(from, to, methodName, input); ``` ### 5. GetFormattedAddress Convert the `Address` to the displayed string format: symbol_base58-string_base58-string_chain-id. +- **Parameters**: + - `address` (string): Address to format + +- **Returns** : + - `string`: Formatted address + +#### Example: + ```csharp -Address address = new Address { Value = Address.FromBase58("ADDRESS").Value }; -string formattedAddress = await client.GetFormattedAddressAsync(address); -Console.WriteLine($"Formatted Address: {formattedAddress}"); +await client.GetFormattedAddressAsync(address); ``` ### 6. SignTransaction +- **Parameters**: + - `privateKey` (string): Address to format + - `transaction` (string): Address to format + +- **Returns** : + - `Transaction` + +#### Example: + ```csharp -string privateKeyHex = "YOUR_PRIVATE_KEY_HEX"; -Transaction signedTransaction = client.SignTransaction(privateKeyHex, transaction); -Console.WriteLine($"Signed Transaction: {signedTransaction}"); +client.SignTransaction(privateKeyHex, transaction); ``` ### 7. GetAddressFromPubKey Get the account address through the public key. +- **Parameters**: + - `pubKey` (string): Public key + +- **Returns** : + - `string`: Account address + +#### Example: + ```csharp -string pubKey = "YOUR_PUBLIC_KEY"; -string addressFromPubKey = client.GetAddressFromPubKey(pubKey); -Console.WriteLine($"Address from PubKey: {addressFromPubKey}"); +client.GetAddressFromPubKey(pubKey); ``` ### 8. GetAddressFromPrivateKey Get the account address through the private key. +- **Parameters**: + - `privateKey` (string): Private key + +- **Returns** : + - `string`: Account address + +#### Example: + ```csharp -string privateKeyHex = "YOUR_PRIVATE_KEY_HEX"; -string addressFromPrivateKey = client.GetAddressFromPrivateKey(privateKeyHex); -Console.WriteLine($"Address from Private Key: {addressFromPrivateKey}"); +client.GetAddressFromPrivateKey(privateKeyHex); ``` ### 9. GenerateKeyPairInfo Generate a new account key pair. +- **Parameters**: None + +- **Returns** : + - `KeyPairInfo` + - `PrivateKey` - string + - `PublicKey` - string + - `Address` - string + +#### Example: ```csharp -var keyPairInfo = client.GenerateKeyPairInfo(); -Console.WriteLine($"Private Key: {keyPairInfo.PrivateKey}"); -Console.WriteLine($"Public Key: {keyPairInfo.PublicKey}"); -Console.WriteLine($"Address: {keyPairInfo.Address}"); +client.GenerateKeyPairInfo(); ``` ## Supports diff --git a/docs/Tools/Chain SDK/Go SDK/index.md b/docs/Tools/Chain SDK/Go SDK/index.md index c87e132e..c48bc49f 100644 --- a/docs/Tools/Chain SDK/Go SDK/index.md +++ b/docs/Tools/Chain SDK/Go SDK/index.md @@ -2,19 +2,18 @@ sidebar_position: 3 title: Go SDK description: Go SDK +image: /img/Logo.aelf.svg --- # 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: @@ -23,7 +22,6 @@ go get -u github.com/AElfProject/aelf-sdk.go ``` ## Examples ----------- ### Create instance @@ -31,15 +29,7 @@ go get -u github.com/AElfProject/aelf-sdk.go 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" -) +import ("github.com/AElfProject/aelf-sdk.go/client") var aelf = client.AElfClient{ Host: "http://127.0.0.1:8000", @@ -52,18 +42,14 @@ var aelf = client.AElfClient{ Here is an example of how to initiate a transfer transaction using the aelf Go SDK: -#### 1. Get the Token Contract Address: ```go +// Get token contract address. 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", @@ -71,30 +57,21 @@ params := &pb.TransferInput{ Memo: "transfer in demo", } paramsByte, _ := proto.Marshal(params) -``` - -#### 3. Generate and Sign the Transaction: -```go +// Generate a transfer transaction. 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)) +// Send the transfer transaction to AElf chain node. +transactionByets, _ := proto.Marshal(transaction) +sendResult, _ := aelf.SendTransaction(hex.EncodeToString(transactionByets)) time.Sleep(time.Duration(4) * time.Second) transactionResult, _ := aelf.GetTransactionResult(sendResult.TransactionID) fmt.Println(transactionResult) -``` - -#### 5. Query Account Balance: -```go +// Query account balance. ownerAddress, _ := util.Base58StringToAddress(fromAddress) getBalanceInput := &pb.GetBalanceInput{ Symbol: "ELF", @@ -107,8 +84,8 @@ getBalanceTransaction.Params = getBalanceInputByte getBalanceSignature, _ := aelf.SignTransaction(aelf.PrivateKey, getBalanceTransaction) getBalanceTransaction.Signature = getBalanceSignature -getBalanceTransactionBytes, _ := proto.Marshal(getBalanceTransaction) -getBalanceResult, _ := aelf.ExecuteTransaction(hex.EncodeToString(getBalanceTransactionBytes)) +getBalanceTransactionByets, _ := proto.Marshal(getBalanceTransaction) +getBalanceResult, _ := aelf.ExecuteTransaction(hex.EncodeToString(getBalanceTransactionByets)) balance := &pb.GetBalanceOutput{} getBalanceResultBytes, _ := hex.DecodeString(getBalanceResult) proto.Unmarshal(getBalanceResultBytes, balance) @@ -118,16 +95,13 @@ 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" -) +import ("github.com/AElfProject/aelf-sdk.go/client") var aelf = client.AElfClient{ Host: "http://127.0.0.1:8000", @@ -143,18 +117,20 @@ var aelf = client.AElfClient{ - **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 +- **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: @@ -206,25 +182,27 @@ 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 + - `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: @@ -239,25 +217,27 @@ block, err := aelf.GetBlockByHash(blockHash, true) - **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 + - `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: @@ -271,30 +251,32 @@ block, err := aelf.GetBlockByHeight(100, true) - **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 + - `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: @@ -311,9 +293,9 @@ Get multiple transaction results in a block. - **Web API path**: `/api/blockChain/transactionResults` - **Parameters** : - - blockHash - string - - offset - int - - limit - int + - `blockHash` - string + - `offset` - int + - `limit` - int - **Returns**: `[]TransactionResultDto` - the transaction result object @@ -330,10 +312,11 @@ transactionResults, err := aelf.GetTransactionResults(blockHash, 0, 10) - **Web API path**: `/api/blockChain/transactionPoolStatus` - **Parameters** : None + - **Returns**: `TransactionPoolStatusOutput` - - Queued - int - - Validated - int + - `Queued` - int + - `Validated` - int #### Example: @@ -347,12 +330,36 @@ poolStatus, err := aelf.GetTransactionPoolStatus(); - **Web API path**: `/api/blockChain/sendTransaction` (POST) - **Parameters** : - - SendRawTransactionInput - struct containing `Transaction` as string, `Signature` as string, and `ReturnTransaction` as bool + - `SendRawTransactionInput` - Serialization of data into protobuf data: + - `RawTransaction` - string + +- **Returns**: + + - `SendTransactionOutput` + - `TransactionId` - string + + +#### Example: + +```go +sendResult, err := aelf.SendTransaction(input) +``` + +### SendRawTransaction + +- **Web API path**: `/api/blockChain/sendTransaction` (POST) + +- **Parameters** : + - `SendRawTransactionInput` - Serialization of data into protobuf data: + - `RawTransaction` - string + - `Signature` - string + - `ReturnTransaction` - bool -- **Returns**: `SendRawTransactionOutput` +- **Returns**: - - TransactionId - string - - Transaction - TransactionDto + - `SendRawTransactionOutput` + - `TransactionId` - string + - `Transaction` - TransactionDto #### Example: @@ -362,12 +369,13 @@ sendRawResult, err := aelf.SendRawTransaction(input) ``` + ### SendTransactions - **Web API path**: `/api/blockChain/sendTransactions` (POST) - **Parameters** : - - rawTransactions - string + - `rawTransactions` - string - - Serialization of data into protobuf data: - **Returns**: `[]interface{}` @@ -387,9 +395,19 @@ Creates an unsigned serialized transaction. - **Web API path**: `/api/blockChain/rawTransaction` (POST) - **Parameters** : - - CreateRawTransactionInput - struct containing `From`, `To`, `RefBlockNumber`, `RefBlockHash`, `MethodName`, `Params` -- **Returns**: `CreateRawTransactionOutput` + - `CreateRawTransactionInput` + - `From` - string + - `To` - string + - `RefBlockNumber` - long + - `RefBlockHash` - string + - `MethodName` - string + - `Params` - string + +- **Returns**: + + - `CreateRawTransactionOutput` + - `RawTransactions` - string #### Example: @@ -407,7 +425,7 @@ Call a read-only method on a contract. - **Web API path**: `/api/blockChain/executeTransaction` (POST) - **Parameters** : - - rawTransaction - string + - `rawTransaction` - string - **Returns**: `string` @@ -427,7 +445,9 @@ 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 + - `ExecuteRawTransactionDto` - Serialization of data into protobuf data: + - `RawTransaction` - string + - `Signature` - string - **Returns**: `string` @@ -443,28 +463,29 @@ executeRawresult, err := aelf.ExecuteRawTransaction(executeRawinput) Get peer info about the connected network nodes. - - **Web API path**: `/api/net/peers` - **Parameters** : - - withMetrics - bool + - `withMetrics` - bool -- **Returns**: `[]PeerDto` +- **Returns**: - - 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 + - `[]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 @@ -483,7 +504,8 @@ Attempts to add a node to the connected network nodes. - **Web API path**: `/api/net/peer` (POST) - **Parameters** : - - ipAddress - string + + - `ipAddress` - string - **Returns**: `bool` @@ -502,7 +524,8 @@ Attempts to remove a node from the connected network nodes. - **Web API path**: `/api/net/peer` (DELETE) - **Parameters** : - - ipAddress - string + + - `ipAddress` - string - **Returns**: `bool` @@ -521,12 +544,14 @@ Estimate transaction fee. - **Web API path**: `/api/blockChain/calculateTransactionFee` (POST) - **Parameters** : - - CalculateTransactionFeeInput - struct containing `RawTransaction` as string + - `CalculateTransactionFeeInput` - The object with the following structure : + - `RawTrasaction` - string -- **Returns**: `TransactionFeeResultOutput` - - Success - bool - - TransactionFee - map[string]interface{} - - ResourceFee - map[string]interface{} +- **Returns**: + - `TransactionFeeResultOutput` + - `Success` - bool + - `TransactionFee` - map[string]interface{} + - `ResourceFee` - map[string]interface{} #### Example: @@ -544,10 +569,12 @@ Get the network information of the node. - **Parameters** : Empty -- **Returns**: `NetworkInfoOutput` - - Version - string - - ProtocolVersion - int - - Connections - int +- **Returns**: + + - `NetworkInfoOutput` + - `Version` - string + - `ProtocolVersion` - int + - `Connections` - int #### Example: @@ -695,7 +722,11 @@ address := aelf.GetAddressFromPrivateKey(privateKey) - **Parameters**: None - **Returns** : - - `KeyPairInfo`: Contains PrivateKey, PublicKey, and Address + + - `KeyPairInfo` + - `PrivateKey` + - `PublicKey` + - `Address` #### Example: diff --git a/docs/Tools/Chain SDK/Java SDK/index.md b/docs/Tools/Chain SDK/Java SDK/index.md index 087f85e0..54d23248 100644 --- a/docs/Tools/Chain SDK/Java SDK/index.md +++ b/docs/Tools/Chain SDK/Java SDK/index.md @@ -1,7 +1,8 @@ --- sidebar_position: 4 -title: Java SDK -description: Java SDK +title: JAVA SDK +description: JAVA SDK +image: /img/Logo.aelf.svg --- # aelf-sdk.java - aelf Java API @@ -48,63 +49,40 @@ boolean isConnected = client.isConnected(); ### Initiate a Transfer Transaction -Initiate a transfer transaction using the following steps: - -#### 1. Get Token Contract Address ```java -Copy code +// Get token contract address. 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 +// Send the transfer transaction to AElf chain node. SendTransactionInput sendTransactionInputObj = new SendTransactionInput(); sendTransactionInputObj.setRawTransaction(Hex.toHexString(transactionTransferObj.toByteArray())); SendTransactionOutput sendResult = client.sendTransaction(sendTransactionInputObj); -``` - -#### 6. Query Execution Results -```java Thread.sleep(4000); +// After the transaction is mined, query the execution results. TransactionResultDto transactionResult = client.getTransactionResult(sendResult.getTransactionId()); System.out.println(transactionResult.getStatus()); -``` -#### 7. Query Account Balance - -```java +// Query account balance. Client.Address.Builder owner = Client.Address.newBuilder(); owner.setValue(ByteString.copyFrom(Base58.decodeChecked(ownerAddress))); Client.Address ownerObj = owner.build(); @@ -225,9 +203,9 @@ Get block information by block hash. - `blockHash` - String - `includeTransactions` - boolean (true to include transaction ids list in the block, false otherwise) -**Returns**: `BlockDto` +**Returns**: - - `json` + - `BlockDto` - `BlockHash` - String - `Header` - BlockHeaderDto - `PreviousBlockHash` - String @@ -261,9 +239,9 @@ client.getBlockByHash(blockHash); - `blockHeight` - long - `includeTransactions` - boolean (true to include transaction ids list in the block, false otherwise) -**Returns**: `BlockDto` +**Returns**: - - `json` + - `BlockDto` - `BlockHash` - String - `Header` - BlockHeaderDto - `PreviousBlockHash` - String @@ -351,10 +329,11 @@ client.getTransactionResults(blockHash, 0, 10); **Parameters:**: None -**Returns**: `TransactionPoolStatusOutput` +**Returns**: -- `Queued` - int -- `Validated` - int + - `TransactionPoolStatusOutput` + - `Queued` - int + - `Validated` - int **Example**: @@ -374,9 +353,10 @@ client.getTransactionPoolStatus(); - `SendTransactionInput` - Serialization of data into protobuf format: - `RawTransaction` - String -**Returns**: `SendTransactionOutput` +**Returns**: -- `TransactionId` - String + - `SendTransactionOutput` + - `TransactionId` - String **Example**: @@ -398,10 +378,11 @@ client.sendTransaction(input); - `Signature` - String - `ReturnTransaction` - boolean -**Returns**: `SendRawTransactionOutput` +**Returns**: - - `TransactionId` - String - - `Transaction` - TransactionDto + - `SendRawTransactionOutput` + - `TransactionId` - String + - `Transaction` - TransactionDto **Example**: @@ -452,9 +433,10 @@ Create an unsigned serialized transaction. - `MethodName` - String - `Params` - String -**Returns**: `CreateRawTransactionOutput` - Serialization of data into protobuf format: +**Returns**: -- `RawTransaction` - String + - `CreateRawTransactionOutput` - Serialization of data into protobuf format: + - `RawTransaction` - String **Example**: @@ -515,22 +497,23 @@ Get peer information about the connected network nodes. - `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 +**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**: @@ -597,12 +580,13 @@ Estimate transaction fee. - `CalculateTransactionFeeInput` - `RawTransaction` - String -**Returns**: `CalculateTransactionFeeOutput` - -- `Success` - boolean -- `TransactionFee` - HashMap`` -- `ResourceFee` - HashMap`` +**Returns**: + - `CalculateTransactionFeeOutput` + - `Success` - boolean + - `TransactionFee` - HashMap`` + - `ResourceFee` - HashMap`` + **Example**: ```java @@ -617,11 +601,12 @@ CalculateTransactionFeeOutput output = client.calculateTransactionFee(input); **Parameters:** None -**Returns**: `NetworkInfoOutput` +**Returns**: -- `Version` - String -- `ProtocolVersion` - int -- `Connections` - int + - `NetworkInfoOutput` + - `Version` - String + - `ProtocolVersion` - int + - `Connections` - int **Example**: @@ -773,11 +758,13 @@ client.getAddressFromPrivateKey(privateKey); **Parameters:** None -**Returns**: `KeyPairInfo` +**Returns**: -- `PrivateKey` - String -- `PublicKey` - String -- `Address` - String + - `KeyPairInfo` + + - `PrivateKey` - String + - `PublicKey` - String + - `Address` - String **Example**: diff --git a/docs/Tools/Chain SDK/JavaScript SDK/index.md b/docs/Tools/Chain SDK/JavaScript SDK/index.md index 20c9c1b5..3e0cd155 100644 --- a/docs/Tools/Chain SDK/JavaScript SDK/index.md +++ b/docs/Tools/Chain SDK/JavaScript SDK/index.md @@ -2,6 +2,7 @@ sidebar_position: 1 title: Javascript SDK description: Javascript SDK +image: /img/Logo.aelf.svg --- # aelf-sdk.js - aelf JavaScript API @@ -170,6 +171,8 @@ You can access the Web API of your aelf node at `{chainAddress}/swagger/index.ht 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`. +parameters and returns based on the URL: [https://aelf-public-node.aelf.io/swagger/index.html](https://aelf-public-node.aelf.io/swagger/index.html) + The methods below use an instance of aelf. If you don't have one, create it as shown: ```javascript @@ -186,7 +189,19 @@ 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. +- **Returns**: `Object` + + - `ChainId` - String + - `Branches` - Object + - `NotLinkedBlocks` - Object + - `LongestChainHeight` - Number + - `LongestChainHash` - String + - `GenesisBlockHash` - String + - `GenesisContractAddress` - String + - `LastIrreversibleBlockHash` - String + - `LastIrreversibleBlockHeight` - Number + - `BestChainHash` - String + - `BestChainHeight` - Number #### Example: @@ -206,7 +221,7 @@ Get the protobuf definitions related to a contract. - **Web API Path**: `/api/blockChain/contractFileDescriptorSet` - **Method**: GET - **Parameters**: `contractAddress` (String) -- **Returns**: String. +- **Returns**: `String`. #### Example: @@ -227,7 +242,7 @@ Get the current best height of the chain. - **Web API Path**: `/api/blockChain/blockHeight` - **Method**: GET - **Parameters**: None -- **Returns**: Number. +- **Returns**: `Number`. #### Example: @@ -246,10 +261,31 @@ Get block information by block hash. - **Web API Path**: `/api/blockChain/block` - **Method**: GET -- **Parameters**: `contractAddress` (String) +- **Parameters**: - **`blockHash`** (String) - **`includeTransactions`** (Boolean) -- **Returns**: object with block details + - `true` require transaction ids list in the block + - `false` Doesn’t require transaction ids list in the block + +- **Returns**: `Object` + + - `BlockHash` - String + + - `Header` - Object + - `PreviousBlockHash` - String + - `MerkleTreeRootOfTransactions` - String + - `MerkleTreeRootOfWorldState` - String + - `Extra` - Array + - `Height` - Number + - `Time` - google.protobuf.Timestamp + - `ChainId` - String + - `Bloom` - String + - `SignerPubkey` - String + + - `Body` - Object + - `TransactionsCount` - Number + - `Transactions` - Array + - `transactionId` - String #### Example: @@ -271,7 +307,29 @@ Get block information by block height. - **Parameters**: - **`blockHash`** (String) - **`includeTransactions`** (Boolean) -- **Returns**: Object with block details + - `true` require transaction ids list in the block + - `false` Doesn’t require transaction ids list in the block + +- **Returns**: `Object` + + - `BlockHash` - String + + - `Header` - Object + - `PreviousBlockHash` - String + - `MerkleTreeRootOfTransactions` - String + - `MerkleTreeRootOfWorldState` - String + - `Extra` - Array + - `Height` - Number + - `Time` - google.protobuf.Timestamp + - `ChainId` - String + - `Bloom` - String + - `SignerPubkey` - String + + - `Body` - Object + - `TransactionsCount` - Number + - `Transactions` - Array + - `transactionId` - String + #### Example: @@ -289,7 +347,27 @@ aelf.chain.getBlockByHeight(12, false) - **Web API Path**: `/api/blockChain/transactionResult` - **Method**: GET - **Parameters**: `transactionId` (String) -- **Returns**: Object with transaction details +- **Returns**: `Object` + + - `TransactionId` - String + - `Status` - String + - `Logs` - Array + - `Address` - String + - `Name` - String + - `Indexed` - Array + - `NonIndexed` - Number + - `Bloom` - String + - `BlockNumber` - Number + - `Transaction` - Object + - `From` - String + - `To` - String + - `RefBlockNumber` - Number + - `RefBlockPrefix` - String + - `MethodName` - String + - `Params` - Object + - `Signature` - String + - `ReadableReturnValue` - Object + - `Error` - String #### Example: @@ -310,7 +388,9 @@ aelf.chain.getTxResult(transactionId) - **`blockHash`** (String) - **`offset`** (Number) - **`limit`** (Number) -- **Returns**: Array of transaction result objects +- **Returns**: + - `Array` - The array of method descriptions: + - the transaction result object #### Example: @@ -328,7 +408,6 @@ aelf.chain.getTxResults(blockHash, 0, 2) - **Web API Path**: `/api/blockChain/transactionPoolStatus` - **Method**: GET - **Parameters**: None -- **Returns**: Object with transaction pool status ### 9. Send Transaction @@ -337,61 +416,65 @@ aelf.chain.getTxResults(blockHash, 0, 2) - **Web API Path**: `/api/blockChain/sendTransaction` - **Method**: POST - **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) -- **Returns**: Transaction ID + - `RawTransaction` - String ### 10. Send Multiple Transactions - - **Web API Path**: `/api/blockChain/sendTransactions` - **Method**: POST - **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) -- **Returns**: Transaction IDs + - `RawTransaction` - String ### 11. Call Read-Only Method +Call a read-only method on a contract. -- **Web API Path**: `/api/blockChain/callReadOnly` - **Method**: POST - **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) + - `RawTransaction` - String - **Returns**: Method call result ### 12. Get Peers +Get peer info about the connected network nodes. -- **Web API Path**: `/api/net/peers` - **Method**: GET - **Parameters**: `withMetrics` (Boolean) -- **Returns**: Array of peer info - + - `true` with metrics + - `false` without metrics + ### 13. Add Peer +Attempts to add a node to the connected network nodes -- **Web API Path**: `/api/net/peer` - **Method**: POST -- **Parameters**: `Object` (Address string) -- **Returns**: Status - +- **Parameters**: `Object` The object with the following structure : + - `Address` - String ### 14. Remove Peer +Attempts to remove a node from the connected network nodes -- **Web API Path**: `/api/net/peer` - **Method**: DELETE - **Parameters**: `address` (String) -- **Returns**: Status -### 15. Send Multiple Transactions +### 15. Calculate Transaction Fee - **Web API Path**: `/api/blockChain/calculateTransactionFee` - **Method**: POST -- **Parameters**: `CalculateTransactionFeeInput` (Object with RawTransaction string) -- **Returns**: `CalculateTransactionFeeOutput` (Object with fee details) +- **Parameters**: `CalculateTransactionFeeInput` (Object with RawTransaction string): + - `RawTransaction` - String +- **Returns**: `CalculateTransactionFeeOutput` (Object with fee details): + - `Success` - Bool + - `TransactionFee` - Array + - `ResourceFee` - Array + #### Example @@ -405,13 +488,11 @@ aelf.chain.calculateTransactionFee(rawTransaction) ### 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`. diff --git a/docs/Tools/Chain SDK/PHP SDK/index.md b/docs/Tools/Chain SDK/PHP SDK/index.md index ee769c4a..3bf88153 100644 --- a/docs/Tools/Chain SDK/PHP SDK/index.md +++ b/docs/Tools/Chain SDK/PHP SDK/index.md @@ -2,6 +2,7 @@ sidebar_position: 5 title: PHP SDK description: PHP SDK +image: /img/Logo.aelf.svg --- # aelf-sdk.php - aelf PHP API @@ -93,7 +94,6 @@ print_r($result); ``` ## Web API ----------- You can access the Web API of your aelf node at: @@ -108,7 +108,7 @@ Before using the methods, make sure you have an instance of AElf: ```php require_once 'vendor/autoload.php'; use AElf\AElf; - +// create a new instance of AElf $url = '127.0.0.1:8000'; $aelf = new AElf($url); ``` @@ -120,11 +120,28 @@ $aelf = new AElf($url); - **Parameters**: None -- **Returns**: Array with chain status details +- **Returns**: + + - `Array` + - `ChainId` - String + - `Branches` - Array + - `NotLinkedBlocks` - Array + - `LongestChainHeight` - Integer + - `LongestChainHash` - String + - `GenesisBlockHash` - String + - `GenesisContractAddress` - String + - `LastIrreversibleBlockHash` - String + - `LastIrreversibleBlockHeight` - Integer + - `BestChainHash` - String + - `BestChainHeight` - Integer + - **Example** : ```php +// create a new instance of AElf +$aelf = new AElf($url); + $chainStatus = $aelf->getChainStatus(); print_r($chainStatus); ``` @@ -142,12 +159,14 @@ print_r($chainStatus); - **Example** : ```php +$aelf = new AElf($url); + $height = $aelf->getBlockHeight(); print($height); ``` -### 3. Get Block by Hash +### 3. getBlock - **API Path**: `/api/blockChain/block` @@ -156,11 +175,30 @@ print($height); - `block_hash` (String) - `include_transactions` (Boolean) -- **Returns**: Array with block information +- **Returns**: + + - `Array` + - `BlockHash` - String + - `Header` - Array + - `PreviousBlockHash` - String + - `MerkleTreeRootOfTransactions` - String + - `MerkleTreeRootOfWorldState` - String + - `Extra` - List + - `Height` - Integer + - `Time` - String + - `ChainId` - String + - `Bloom` - String + - `SignerPubkey` - String + - `Body` - Array + - `TransactionsCount` - Integer + - `Transactions` - Array + - `transactionId` - String - **Example** : ```php +$aelf = new AElf($url); + $block = $aelf->getBlockByHeight(1, true); $block2 = $aelf->getBlockByHash($block['BlockHash'], false); print_r($block2); @@ -176,11 +214,31 @@ print_r($block2); - `block_height` (Number) - `include_transactions` (Boolean) -- **Returns**: Array with block information +- **Returns**: + + - `Array` + - `BlockHash` - String + - `Header` - Array + - `PreviousBlockHash` - String + - `MerkleTreeRootOfTransactions` - String + - `MerkleTreeRootOfWorldState` - String + - `Extra` - List + - `Height` - Integer + - `Time` - String + - `ChainId` - String + - `Bloom` - String + - `SignerPubkey` - String + - `Body` - Array + - `TransactionsCount` - Integer + - `Transactions` - Array + - `transactionId` - String + - **Example** : ```php +$aelf = new AElf($url); + $block = $aelf->getBlockByHeight(1, true); print_r($block); ``` @@ -194,11 +252,35 @@ print_r($block); - `transactionId` (String) -- **Returns**: Object with transaction result details +- **Returns**: + + - `Object` + - `TransactionId` - String + - `Status` - String + - `Logs` - Array + - `Address` - String + - `Name` - String + - `Indexed` - Array + - `NonIndexed` - String + - `Bloom` - String + - `BlockNumber` - Integer + - `Transaction` - Array + - `From` - String + - `To` - String + - `RefBlockNumber` - Integer + - `RefBlockPrefix` - String + - `MethodName` - String + - `Params` - json + - `Signature` - String + - `transactionId` - String + - `ReadableReturnValue` - String + - `Error` - String - **Example** : ```php +$aelf = new AElf($url); + $block = $aelf->getBlockByHeight(1, true); $transactionResult = $aelf->getTransactionResult($block['Body']['Transactions'][0]); print_r($transactionResult); @@ -215,11 +297,16 @@ print_r($transactionResult); - `offset` (Number) - `limit` (Number) -- **Returns**: List of transaction result objects +- **Returns**: + + - `List` - The array of method descriptions: + - the transaction result object - **Example** : ```php +$aelf = new AElf($url); + $block = $aelf->getBlockByHeight(1, true); $transactionResults = $aelf->getTransactionResults($block['Body']); print_r($transactionResults); @@ -233,6 +320,8 @@ print_r($transactionResults); - **Example** : ```php +$aelf = new AElf($url); + $status = $aelf->getTransactionPoolStatus(); print_r($status); ``` @@ -273,6 +362,8 @@ print_r($result); - **Example** : ```php +$aelf = new AElf($url); + $paramsList = [$params1, $params2]; $rawTransactionsList = []; foreach ($paramsList as $param) { @@ -339,11 +430,16 @@ $aelf->removePeer($url); - `transaction` (Array) -- **Returns**: Array with the raw transaction hex string +- **Returns**: + + - `Array` + - `RawTransaction` - hex string bytes generated by transaction information - **Example** : ```php +$aelf = new AElf($url); + $status = $aelf->getChainStatus(); $params = base64_encode(hex2bin(hash('sha256', 'AElf.ContractNames.Consensus'))); $param = array('value' => $params); @@ -373,6 +469,8 @@ print_r($rawTransaction); - **Example** : ```php +$aelf = new AElf($url); + $rawTransaction = $aelf->createRawTransaction($transaction); $transactionId = hash('sha256', hex2bin($rawTransaction['RawTransaction'])); $sign = $aelf->getSignatureWithPrivateKey($privateKey, $transactionId); @@ -398,6 +496,8 @@ print_r($execute); - **Example** : ```php +$aelf = new AElf($url); + $rawTransaction = $aelf->createRawTransaction($transaction); $transactionId = hash('sha256', hex2bin($rawTransaction['RawTransaction'])); $sign = $aelf->getSignatureWithPrivateKey($privateKey, $transactionId); @@ -418,6 +518,8 @@ print_r($execute); - **Example** : ```php +$aelf = new AElf($url); + $block = $aelf->getBlockByHeight(1, true); $merklePath = $aelf->getMerklePathByTransactionId($block['Body']['Transactions'][0]); print_r($merklePath); @@ -434,11 +536,19 @@ print_r($merklePath); - `CalculateTransactionFeeInput` (Object) -- **Returns**: `CalculateTransactionFeeOutput (Object)` +- **Returns**: + + - `CalculateTransactionFeeOutput (Object)` + + - `Success` - bool + - `TransactionFee` - Array + - `ResourceFee` - Array - **Example** : ```php +$aelf = new AElf($url); + $calculateTransactionFeeInputParam = [ "rawTransaction" => $rawTransactionInput, ]; @@ -454,6 +564,8 @@ print_r($result); - **Example** : ```php +$aelf = new AElf($url); + print_r($aelf->getNetworkInfo()); ``` diff --git a/docs/Tools/Chain SDK/Python SDK/index.md b/docs/Tools/Chain SDK/Python SDK/index.md index f2e71d82..004196d6 100644 --- a/docs/Tools/Chain SDK/Python SDK/index.md +++ b/docs/Tools/Chain SDK/Python SDK/index.md @@ -2,6 +2,7 @@ sidebar_position: 6 title: Python SDK description: Python SDK +image: /img/Logo.aelf.svg --- # aelf-sdk.py - aelf Python API diff --git a/docs/Understanding aelf/Addresses/index.md b/docs/Understanding aelf/Addresses/index.md index c5633385..2a3e0904 100644 --- a/docs/Understanding aelf/Addresses/index.md +++ b/docs/Understanding aelf/Addresses/index.md @@ -1,8 +1,9 @@ --- sidebar_position: 5 title: Addresses +description: Addresses +image: /img/Logo.aelf.svg --- - # Address ### Overview diff --git a/docs/Understanding aelf/Network/index.md b/docs/Understanding aelf/Network/index.md index 40949a62..970ae07b 100644 --- a/docs/Understanding aelf/Network/index.md +++ b/docs/Understanding aelf/Network/index.md @@ -1,6 +1,8 @@ --- sidebar_position: 4 title: Network +description: Network +image: /img/Logo.aelf.svg --- # Network diff --git a/docs/Understanding aelf/Transactions/index.md b/docs/Understanding aelf/Transactions/index.md index 1550067f..182c5176 100644 --- a/docs/Understanding aelf/Transactions/index.md +++ b/docs/Understanding aelf/Transactions/index.md @@ -1,6 +1,8 @@ --- sidebar_position: 6 title: Transactions +description: Transactions +image: /img/Logo.aelf.svg --- # Overview