VAR-META-Tech / Aptos-Cpp-SDK

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

AptosUnitySDKLogo

Aptos-Cpp-SDK

Aptos-Cpp-SDK is a cpp package written in C++ to help developers integrate Aptos blockchain technology into their cpp and Unreal projects.

Project Layout

  1. AptosSDKDemo/:: This directory contains examples showcasing how to use the Aptos Cpp SDK.
  2. AptosUI/:: This directory contains Wallet example Unreal Project using Aptos Cpp SDK.
  3. Doc/:: Documentation related to the project, which include setup API, Class references.
  4. Resource/:: A place for various resources needed for the project, like images, data files, or other assets.
  5. Src/: Contains the main source code for the SDK. This is where you'll find the core functionality, client classes, and utility modules.
  6. ThirdParty/: Holds unit tests and integration tests for verifying the correctness of your code. Writing comprehensive tests ensures robustness.

Features

  • Generate new wallets.
  • Create new accounts using the ED25519 Key Standard.
  • Simulate and submit transaction.
  • Create new collections.
  • Create new tokens.
  • Check account information (Token and APT balances, submitted contracts, etc).
  • Import previously used wallets using BIP-39 and BIP-32 Mnemonic seeds or an ED25519 private key.
  • Create arbitrary tokens.
  • Compatibility with main, dev, and test networks.
  • Comprehensive Unit and Integration Test coverage.

Requirements

Platforms Unreal Version Installation Status
Mac / Linux Unity engine 5.3 3rd lib build config Fully Tested

Dependencies

Installation

Installation Guide

This guide provides step-by-step instructions for installing and setting up our library which is compatible with Windows, Linux, and macOS platforms. Ensure you have the following prerequisites installed to build the project:

Prerequisites

All Platforms

  • Conan: C++ Package Manager

Windows Specific

  • CMake (version 3.14 or higher)
  • Visual Studio with C++ development environment

Linux/macOS Specific

  • CMake (version 3.14 or higher)

Additionally, for macOS, to perform code coverage, you'll need LLVM and lcov.

Installation Steps

Windows

  1. Install Visual Studio with the C++ development environment.
  2. Install CMake if not included in the Visual Studio installation.
  3. Install Conan using pip or download it from the official website.

Linux

  1. Install CMake and Conan using your distribution's package manager.

macOS

  1. Install Homebrew (if not already installed):
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  2. Install CMake and Conan using Homebrew:
    brew install cmake conan
  3. For code coverage tools, install LLVM and lcov:
    brew install llvm lcov

Project Setup

Follow these steps to set up the project environment:

  1. Clone the repository and initialize submodules:

    git clone <repository-url>
    cd <repository-name>
    git submodule update --init --recursive
  2. Install the project dependencies using Conan:

    conan install . -s compiler.cppstd=20 --build=missing
  3. Build the project:

    cd build
    cmake ..

    Windows

    Open the solution file .sln in Visual Studio and build the project using the IDE's build tools. (Currently only support build Release)

    Linux/macOS

    Once the environment is set up, you can use the following make options:

    Builds all the libraries of the project.

    make build

    Runs the unit tests and integration tests.

    make test

    Executes a sample demo to showcase features used in the SDK.

    make demo

macOS Specific Instructions

If you encounter any errors regarding the 'macos' path not being found, you can update the conan_toolchain.cmake file as follows:

set(CMAKE_OSX_SYSROOT /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk CACHE STRING "" FORCE)

#For run code coverage on MacOS First of all, make sure you have llvm and lcov installed. You can install them using brew: brew install llvm lcov To generate coverage data, you would then do: cmake -DCODE_COVERAGE=ON .. make make coverage

Example Unreal Project

A examples unreal project can be found in the following directory:
AptosUI/.

For Unreal project please reference example in AptosUI, you need define Build.cs to integration Aptos library with Unreal engine. Here is an example:

using UnrealBuildTool;
using System.IO;

public class AptosUI : ModuleRules
{
	public AptosUI(ReadOnlyTargetRules Target) : base(Target)
	{
		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
		bEnableExceptions = true;
		PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "UMG" });
		PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
		PrivateDependencyModuleNames.AddRange(new string[] { });
		if (Target.Platform == UnrealTargetPlatform.Mac)
        {
			string AptosUiLogicPath = Path.Combine(ModuleDirectory, "../../../build/", "libAptosUILogic.dylib");
			string AptosLibPath = Path.Combine(ModuleDirectory, "../../../build/", "libAptos.dylib");
			string Bip3xLibPath = Path.Combine(ModuleDirectory, "../../../Plugins/lib/", "libbip3x.dylib");
			string destinationDirectory = Target.ProjectFile.Directory.FullName;
			File.Copy(AptosUiLogicPath, Path.Combine(destinationDirectory, "libAptosUILogic.dylib"), true);
			File.Copy(AptosLibPath, Path.Combine(destinationDirectory, "libAptos.dylib"), true);
			File.Copy(Bip3xLibPath, Path.Combine(destinationDirectory, "libbip3x.dylib"), true);

			PublicIncludePaths.AddRange(new string[] { Path.Combine(ModuleDirectory, "../../../") });
			PublicAdditionalLibraries.Add(Path.Combine(destinationDirectory, "libAptos.dylib"));
			PublicAdditionalLibraries.Add(Path.Combine(destinationDirectory, "libAptosUILogic.dylib"));
			PublicAdditionalLibraries.Add(Path.Combine(destinationDirectory, "libbip3x.dylib"));
        }

		PublicIncludePaths.AddRange(new string[] { "/usr/local/include/" });
		bEnableUndefinedIdentifierWarnings = false;
		CppStandard = CppStandardVersion.Cpp17;
	}
}

Video we using SDK on windows with sample unreal project:

0329.mp4

Using Aptos-Cpp-SDK

Aptos-Cpp-SDK can integrate into your own any cpp or Unreal projects. The main functionality comes from several key classes: RestClient, FacetClient, TokenClient, EntryFunction, Account, and Wallet.

There are three core client classes:

  • FaucetClient - used to request for airdrops
  • RESTClient - used to query the aptos blockchain

Let's go over each of the classes, along with examples for each to demonstrate their power and flexibility.

RestClient

The REST Client provides you with the fundamental transaction endpoints needed for interacting with the Aptos Blockchain. The following showcases how to initialize the RestClient and AptosTokenClient.

RestClient restClient;
restClient.SetEndpoint(Constants::DEVNET_BASE_URL);

As shown before, it only take a few lines of code to initialize a transfer for Aptos coins. This is the main class developers will be leveraging to interact directly with the Aptos Blockchain via REST Client calls.

AptosRESTModel::Transaction createCollectionTxn;
AptosRESTModel::ResponseInfo responseInfo;
m_restClient.CreateCollection([&](AptosRESTModel::Transaction _createCollectionTxn, AptosRESTModel::ResponseInfo _responseInfo)
                              {
                                  createCollectionTxn = _createCollectionTxn;
                                  responseInfo = _responseInfo; },
                              wallet->Account(),
                              _collectionName, _collectionDescription, _collectionUri);
bool success = false;
if (responseInfo.status == AptosRESTModel::ResponseInfo::Status::Success)
{
    success = true;
}
else
{
    success = false;
}

FaucetClient

The Faucet Client allows the developer to leverage the ability to fund wallets on any of the non-main networks within the Aptos Blockchain. This can easily speed up development times through automating the process of funding wallets. Here's an example on how to use the Faucet Client:

std::string faucetEndpoint = "https://faucet.devnet.aptoslabs.com";
Aptos::Rest::FaucetClient::FundAccount([amount](bool success, AptosRESTModel::ResponseInfo)
                                       {
                                           if (success) {
                                               std::cout << "Successfully Get Airdrop of " << (float)amount << " APT" << std::endl;
                                           } else {
                                               std::cout << "airdrop failed" << std::endl;
                                           } },
                                       wallet->Account().getAccountAddress()->ToString(),
                                       amount,
                                       faucetEndpoint);

TokenClient

EntryFunction

If a developer needs more flexibility with how they want to shape their transactions, e.g., arbitrary, generic, custom, using EntryFunction is the key class, along with the usage of the REST Client, to submit those types of transactions that aren't defined already. This is how the developer would initialize the transaction arguments, create the EntryFunction payload, and submit the transaction using BCS:

std::vector<std::shared_ptr<ISerializable>> transactionArguments;
transactionArguments.push_back(std::make_shared<AccountAddress>(Recipient));
transactionArguments.push_back(std::make_shared<U64>(Amount));
EntryFunction payload = EntryFunction::Natural(
    ModuleId(AccountAddress::FromHex("0x1"), "aptos_account"),
    "transfer",
    TagSequence({}),
    Sequence(transactionArguments));
std::shared_ptr<SignedTransaction> signedTransaction = nullptr;
CreateBCSSignedTransaction([&signedTransaction](std::shared_ptr<SignedTransaction> _signedTransaction)
                           { signedTransaction = _signedTransaction; },
                           Sender, TransactionPayload(std::make_shared<EntryFunction>(payload)));
AptosRESTModel::ResponseInfo responseInfo;
std::string submitBcsTxnJsonResponse = "";
SubmitBCSTransaction([&responseInfo, &submitBcsTxnJsonResponse](std::string _responseJson,
                                                                AptosRESTModel::ResponseInfo _responseInfo)
                     {
submitBcsTxnJsonResponse = _responseJson;
responseInfo = _responseInfo; },
                     *signedTransaction);

Wallet

Wallets will be the primary method of accessing accounts on the Aptos Blockchain via Mnemonic Keys, since they'll allow you to generate multiple accounts with ease. Here's an example on how to initialize a wallet using a mnemonic key:

// Initializing Wallet.
std::string mnemo = "stadium valid laundry unknown tuition train december camera fiber vault sniff ripple";
Wallet* wallet = new Wallet(mnemo);

// Initialize A Random Wallet.
bip3x::bip3x_mnemonic::mnemonic_result mnemonic = bip3x::bip3x_mnemonic::generate();
Wallet* wallet = new Wallet(mnemonic.raw);

This provides the developer with what's known as an HD Wallet (Hierarchical Deterministic Wallet), which is what will enable to generate as many private keys from the wallet as they want. Here's different ways on how to retrieve the account(s) from the Wallet, along with deriving the mnemonic seed from the Wallet; which is the seed that's derived from the input mnemonic phrase and is what allows the developer to generate a number accounts from the Wallet:

// Get the Initial Main Account.
auto mainAccount = wallet->Account();

// Get Any Other Accounts Created / Derived From the Wallet (i represents the index from 0).
auto account = wallet->GetDerivedAccount(i);

// Derive Mnemonic Seed from Wallet.
auto seed = wallet->DeriveMnemonicSeed();

The Wallet object can also allow the main account to sign and verify data, as shown here:

// Initialize a Signature Object.
static const std::vector<uint8_t> MessageUt8Bytes = {
    87, 69, 76, 67, 79, 77, 69, 32,
    84, 79, 32, 65, 80, 84, 79, 83, 33 };
auto acct = wallet->Account();
Signature signature = acct.Sign(Utils::ByteVectorToSecBlock(MessageUt8Bytes));

// Initialize a Boolean Verified.
bool verified = acct.Verify(MessageUt8Bytes, signature);

Using Aptos-Cpp-SDK with Blueprint

Create Wallet

Import Wallet

Send Transaction

Create Collection

Create NFT

Airdrop

Examples

The SDK comes with several examples that show how to leverage the SDK to its full potential. The examples include AptosToken, Multisig, SimulateTransferCoin, TransferCoin, and SimpleNftExample.

AptosDemo.mp4

License

This project is licensed under the Apache-2.0 License. Refer to the LICENSE.txt file for details.

About

License:Apache License 2.0


Languages

Language:HTML 92.0%Language:C++ 7.7%Language:CMake 0.2%Language:C# 0.1%Language:C 0.0%