diff --git a/docs/index.md b/docs/index.md index 02438102..cb9c426f 100644 --- a/docs/index.md +++ b/docs/index.md @@ -17,7 +17,7 @@ aelf is a high-performance, cloud-native, layer-1 blockchain with Mainnet nodes
-
+
## 🏁 Quick Start @@ -31,10 +31,11 @@ aelf is a high-performance, cloud-native, layer-1 blockchain with Mainnet nodes - [Set up](/quick-start/node-operators/set-up-a-node-on-mainnet/) a node on mainnet - [Apply](/quick-start/node-operators/apply-to-be-a-bp/) to be a BP - [Set up](/quick-start/node-operators/set-up-a-side-chain/) a side chain + - [Run](/quick-start/node-operators/run-aelf-on-cloud/) aelf on Cloud
-
+
## 📚 Understanding aelf @@ -50,16 +51,7 @@ aelf is a high-performance, cloud-native, layer-1 blockchain with Mainnet nodes
-
- -## 📖 Tutorials - -- [Operate a Node](/tutorials/operate-a-node/) - - Run aelf on [Cloud](/tutorials/operate-a-node/run-aelf-on-cloud/) - -
- -
+
## 🛠️ Tools @@ -76,7 +68,7 @@ aelf is a high-performance, cloud-native, layer-1 blockchain with Mainnet nodes
-
+
## 🔖 Resources diff --git a/docs/tutorials/operate-a-node/run-aelf-on-cloud/index.md b/docs/quick-start/node-operators/run-aelf-on-cloud/index.md similarity index 96% rename from docs/tutorials/operate-a-node/run-aelf-on-cloud/index.md rename to docs/quick-start/node-operators/run-aelf-on-cloud/index.md index fa2c9e00..7815171a 100644 --- a/docs/tutorials/operate-a-node/run-aelf-on-cloud/index.md +++ b/docs/quick-start/node-operators/run-aelf-on-cloud/index.md @@ -1,9 +1,8 @@ --- -sidebar_position: 3 +sidebar_position: 6 title: Run aelf on Cloud description: Google Cloud Platform (GCP) --- -# Getting Started with Google Cloud This guide will walk you through the steps required to run an aelf node on Google Cloud Platform (GCP). diff --git a/docs/tutorials/developers/_category_.json b/docs/tutorials/developers/_category_.json deleted file mode 100644 index 14345aea..00000000 --- a/docs/tutorials/developers/_category_.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "position": 1, - "label": "For Developers", - "collapsible": true, - "collapsed": true, - "link": { - "type": "generated-index", - "title": "Develop on aelf", - "slug": "tutorials/developers" - }, - "customProps": { - "description": "Develop on aelf" - } -} diff --git a/docs/tutorials/developers/csharp-sdk/index.md b/docs/tutorials/developers/csharp-sdk/index.md deleted file mode 100644 index a9354b61..00000000 --- a/docs/tutorials/developers/csharp-sdk/index.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/tutorials/developers/go-sdk/index.md b/docs/tutorials/developers/go-sdk/index.md deleted file mode 100644 index 1e1d8f4d..00000000 --- a/docs/tutorials/developers/go-sdk/index.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/tutorials/developers/java-sdk/index.md b/docs/tutorials/developers/java-sdk/index.md deleted file mode 100644 index aa4dbb4a..00000000 --- a/docs/tutorials/developers/java-sdk/index.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/tutorials/developers/javascript-sdk/index.md b/docs/tutorials/developers/javascript-sdk/index.md deleted file mode 100644 index f9a7e830..00000000 --- a/docs/tutorials/developers/javascript-sdk/index.md +++ /dev/null @@ -1,836 +0,0 @@ ---- -sidebar_position: 1 -title: Javascript SDK -description: Javascript SDK -image: /img/Logo.aelf.svg ---- - -# aelf-web3.js - aelf JavaScript API - -## Introduction - -The `aelf-web3.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-web3.js`. - -- Understand the available API. - -For more details, check out the repository: [aelf-web3.js](https://github.com/AElfProject/aelf-web3.js). - -## Quickstart - -### 1. Adding aelf-web3.js - -Now, You can add `aelf-web3.js` using **npm** or directly in your **HTML**. - -- #### Using npm - -```bash -npm install aelf-sdk -``` - -- #### Using Pure js - -```bash -link dist/aelf.umd.js -``` - -### 2. Create an AElf Instance - -Set up your AElf instance and connect to a provider. - -#### Node.js - -```js -const AElf = require("aelf-sdk"); -const aelf = new AElf( - new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io") -); -``` - -#### Frontend (Using PureJs) - -- Include the script in your HTML file: - -```js - - -``` - -### 3. Choose the Right Package - -You can skip this step, if Adding aelf-web3.js is enough - -The `dist` directory provides packages for different environments. - -| packages | usage | -| ---------------- | -------------------------------------------------------- | -| dist/aelf.cjs.js | For node.js, excludes node built-in modules like crypto. | -| dist/aelf.umd.js | For browsers, includes necessary node built-in modules. | - -#### For Beginner in Frontend - -- Add the UMD package to your HTML: - -```html - - -``` - -### 4. Use with Bundlers - -If you want to use a bundler like Webpack or Rollup, import the specified version of the package files. - -#### For Browser (Using UMD) - -- Set up Webpack: - -```javascript -module.exports = { - resolve: { - alias: { - "aelf-sdk$": "aelf-sdk/dist/aelf.umd.js", - }, - }, -}; -``` - -- Set up Rollup: - -```javascript -const alias = require("rollup-plugin-alias"); - -rollup({ - // ... - plugins: [ - alias({ - "aelf-sdk": require.resolve("aelf-sdk/dist/aelf.umd.js"), - }), - ], -}); -``` - -#### For Node.js (Using CommonJS) - -- Set up Webpack: - -```javascript -module.exports = { - // ... - resolve: { - alias: { - "aelf-sdk$": "aelf-sdk/dist/aelf.cjs.js", - }, - }, -}; -``` - -- Set up Rollup: - -```javascript -const alias = require("rollup-plugin-alias"); - -rollup({ - // ... - plugins: [ - alias({ - "aelf-sdk": require.resolve("aelf-sdk/dist/aelf.cjs.js"), - }), - ], -}); -``` - -#### Note - -- `aelf-web3.js` is the same as `aelf-sdk`. -- `aelf-sdk` is the package name on npm. - -For more detailed usage and examples, refer to the [aelf-web3.js repository](https://github.com/AElfProject/aelf-web3.js). - -## Development 🔨 - -### 1. Install Development Dependencies - -- install the required development dependencies: - -```bash -yarn install -``` - -### 2. Write Your Code - -- Create your file under the `src` directory. -- Write your logic in the newly created file. - -### 3. Integrate Your Module - -- Check `src/index` to see if you need to add your new module as an attribute to the `AElf` instance. - -### 4. Link the Package Globally - -- Execute `yarn link` in the root directory. This creates a global symbolic link to this package and stores it in the global `node_modules` directory. - -```sh -yarn link -``` - -### 5. Link the Package in Other Directories - -- When using `yarn link aelf-sdk` in other directories, ensure the version of the package is correct. Inconsistent node versions can sometimes cause issues with linking the incorrect version of `aelf-web3.js`. - -```sh -yarn link aelf-sdk -``` - -### 6. Test Your Code - -- Try out the logic you just wrote to make sure everything works as expected. - -### Linting - -- To lint your code, run: - -```sh -yarn lint -``` - -### Running Tests - -- To run unit tests, execute: - -```sh -# Unit tests -yarn test -``` - -## Basic usage - -### Examples - -You can also see full example here - [Examples](https://github.com/AElfProject/aelf-web3.js/tree/master/examples) - -#### Create Instance - -```javascript -import AElf from "aelf-sdk"; - -// Create a new instance of AElf -const aelf = new AElf( - new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io") -); -``` - -#### 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("https://tdvw-test-node.aelf.io") -); -aelf.setProvider( - new AElf.providers.HttpProvider("https://tdvw-test-node.aelf.io") -); -``` - -## Web API - -Access the Web API of your aelf node at `{chainAddress}/swagger/index.html` - -**Examples:** - -- Local node: `http://127.0.0.1:1235/swagger/index.html` -- Testnet nodes: - - **Main Chain**: [https://aelf-test-node.aelf.io/swagger/index.html](https://aelf-test-node.aelf.io/swagger/index.html) - - **Side Chain**: [https://tdvw-test-node.aelf.io/swagger/index.html](https://tdvw-test-node.aelf.io/swagger/index.html) - -**Setup:** - -Create an instance of `AElf`: - -```javascript -import AElf from "aelf-sdk"; - -// 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 Contract View Method List - -- **Web API Path**: `/api/blockChain/ContractViewMethodList` -- **Method**: GET -- **Parameters**: `address` (String) -- **Returns**: `Array` - The array of view method name - -#### Example: - -```javascript -aelf.chain - .getContractViewMethodList("https://tdvw-test-node.aelf.io/") - .then((res) => { - console.log(res); - }); -``` - -### 7. 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); -}); -``` - -### 8. Get Merkle Path By TxId - -- **Web API Path**: `/api/blockChain/merklePathByTransactionId` -- **Method**: GET -- **Parameters**: - - **`transactionId`** (String) -- **Returns**: - - `MerklePathNodes` - The array of merklePathNodes: - - `Hash` - String - - `IsLeftChildNode` - String - -#### Example: - -```javascript -aelf.chain.merklePathByTransactionId(txId).then((res) => { - console.log(res); -}); -``` - -### 9. 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); -}); -``` - -### 10. Get Transaction Pool Status - -- **Web API Path**: `/api/blockChain/transactionPoolStatus` -- **Method**: GET -- **Parameters**: None - -### 11. Send Transaction - -- **Web API Path**: `/api/blockChain/sendTransaction` -- **Method**: POST -- **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) - - `RawTransaction` - String - -### 12. Send Multiple Transactions - -- **Web API Path**: `/api/blockChain/sendTransactions` -- **Method**: POST -- **Parameters**: `Object` (Serialized protobuf data with RawTransaction string) - - `RawTransaction` - String - -### 13. 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 - -### 14. Get Peers - -Get peer info about the connected network nodes. - -- **Method**: GET -- **Parameters**: `withMetrics` (Boolean) - - `true` with metrics - - `false` without metrics - -### 15. Add Peer - -Attempts to add a node to the connected network nodes - -- **Method**: POST -- **Parameters**: `Object` The object with the following structure : - - `Address` - String - -### 16. Remove Peer - -Attempts to remove a node from the connected network nodes - -- **Method**: DELETE -- **Parameters**: `address` (String) - -### 17. 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](../../../resources/contribution/index.md) - -## About Version - -AElf SDK follows Semantic Versioning. For more details, refer to [semver.org](https://semver.org/). diff --git a/docs/tutorials/developers/php-sdk/index.md b/docs/tutorials/developers/php-sdk/index.md deleted file mode 100644 index faac9aba..00000000 --- a/docs/tutorials/developers/php-sdk/index.md +++ /dev/null @@ -1,752 +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](../../../resources/contribution/index.md) - -## About Version - -[https://semver.org/](https://semver.org/) diff --git a/docs/tutorials/developers/python-sdk/index.md b/docs/tutorials/developers/python-sdk/index.md deleted file mode 100644 index 1d09eac0..00000000 --- a/docs/tutorials/developers/python-sdk/index.md +++ /dev/null @@ -1,805 +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 - - `transactionId` - String - -**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 - - `transactionId` - String - -**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` - -**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) -``` - -### 17. Calculate Transaction Fee - -**Web API Path**: `/api/blockchain/calculateTransactionFee` - -**Method**: POST - -**Parameters**: - -- `CalculateTransactionFeeInput` - JSON with the following structure: - - `RawTransaction` - String - -**Returns**: - -- `CalculateTransactionFeeOutput` - `json` - The 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) -``` - -### 18. Get Network Info - -**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](https://www.python.org/) -- [Docker](https://www.docker.com/) - -## Support - -- [Node](https://hub.docker.com/r/aelf/node) - -## About Contributing - -Read out [contributing guide](../../../resources/contribution/index.md) - -## About Version - -[https://semver.org/](https://semver.org/) diff --git a/docs/tutorials/operate-a-node/_category_.json b/docs/tutorials/operate-a-node/_category_.json deleted file mode 100644 index d268a960..00000000 --- a/docs/tutorials/operate-a-node/_category_.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "position": 2, - "label": "For Node Operators", - "collapsible": true, - "collapsed": true, - "link": { - "type": "generated-index", - "title": "Operate a node", - "slug": "tutorials/operate-a-node" - }, - "customProps": { - "description": "Operate a node" - } -} diff --git a/sidebars.ts b/sidebars.ts index 603c5b5b..df8f546f 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -35,16 +35,6 @@ const sidebars: SidebarsConfig = { }, items: [{ type: "autogenerated", dirName: "learn" }], }, - { - type: "category", - label: "Tutorials", - collapsible: false, - link: { - type: "generated-index", - slug: "/tutorials", - }, - items: [{ type: "autogenerated", dirName: "tutorials" }], - }, ], tools: [ {