### Configure Test Example SC Index and Address Source: https://github.com/qubic/core/blob/main/test/README.md This snippet demonstrates how to configure the index and address for the `TESTEXA` smart contract within the `qubic-cli` test utility. These definitions are crucial for correctly referencing the `TESTEXA` SC during testing and may need updates as new SCs are added. ```c++ #define TESTEXA_CONTRACT_INDEX #define TESTEXA_ADDRESS "" ``` -------------------------------- ### Qubic QPI Context Function Call Examples Source: https://github.com/qubic/core/blob/main/doc/contracts.md Shows examples of using the `QpiContextFunctionCall` object within a user function to retrieve contract information like epoch, tick, entity balances, and asset share counts. ```c++ PUBLIC_FUNCTION(GET_INFO) { int current_epoch = qpi.epoch(); int current_tick = qpi.tick(); // Assuming '0x123...' is a valid entity ID auto entity_info = qpi.getEntity("0x123..."); int balance = entity_info.incomingAmount - entity_info.outgoingAmount; size_t share_count = qpi.numberOfShares(); // Use the retrieved information... output.info = "Epoch: " + std::to_string(current_epoch) + ", Balance: " + std::to_string(balance); } ``` -------------------------------- ### Bugfix External Tool Example (Bash) Source: https://github.com/qubic/core/blob/main/doc/contracts.md An example of an external tool written in Bash that can be used to adjust smart contract state files during an epoch transition for bugfixes. This tool must have publicly available source code. ```bash #!/bin/bash # Example Bash external tool for state file adjustment # This is a conceptual example and would need specific implementation details # based on the contract's state structure. if [ "$#" -ne 2 ]; then echo "Usage: $0 " >&2 exit 1 fi INPUT_FILE="$1" OUTPUT_FILE="$2" # Check if input file exists if [ ! -f "$INPUT_FILE" ]; then echo "Error: Input file '$INPUT_FILE' not found." >&2 exit 1 fi # --- State Adjustment Logic --- # This section would contain the specific logic to read the old state, # modify it (e.g., add new fields, reorder), and write the new state. # Bash is generally not ideal for complex binary manipulation, but simple # operations like copying or appending might be feasible. # Example: Simply copy the input file to the output file. # For more complex modifications, consider using tools like 'dd' or scripting # with Python/Perl for binary data handling. cp "$INPUT_FILE" "$OUTPUT_FILE" # Example: Appending new zero-initialized data (conceptual) # This would require knowing the exact byte representation and size of new fields. # For instance, appending 4 null bytes (representing zeroed data): # printf "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" >> "$OUTPUT_FILE" # Appends 16 zero bytes if [ $? -eq 0 ]; then echo "State file adjusted successfully." else echo "Error during state file adjustment." >&2 exit 1 fi exit 0 ``` -------------------------------- ### Enable Test Example SCs in Qubic Core Source: https://github.com/qubic/core/blob/main/test/README.md This code snippet shows how to enable testing of components not covered by unit tests by including test example smart contracts. It involves defining `INCLUDE_CONTRACT_TEST_EXAMPLES` before including `contract_def.h` in `qubic.cpp`. ```c++ #define INCLUDE_CONTRACT_TEST_EXAMPLES #include "contract_def.h" ``` -------------------------------- ### Asset Operations in C++ Source: https://context7.com/qubic/core/llms.txt Provides examples of querying asset ownership and iterating through asset holders using Qubic's Asset Programming Interface (QPI). It covers functions to get the number of owned shares and to list holders with their respective amounts, with a limit on the number of holders returned. ```cpp // Query number of shares owned PUBLIC_FUNCTION(GetOwnedShares) { Asset asset; asset.issuer = input.issuer; asset.assetName = input.assetName; AssetOwnershipSelect ownership = AssetOwnershipSelect::byOwner(input.owner); AssetPossessionSelect possession = AssetPossessionSelect::any(); output.shareCount = qpi.numberOfShares(asset, ownership, possession); } // Iterate through asset ownership records PUBLIC_FUNCTION_WITH_LOCALS(ListAssetHolders) { Asset asset; asset.issuer = input.issuer; asset.assetName = input.assetName; AssetPossessionIterator iter(asset); locals.count = 0; while (!iter.reachedEnd() && locals.count < 64) { output.holders.set(locals.count, iter.possessor()); output.amounts.set(locals.count, iter.numberOfPossessedShares()); locals.count = locals.count + 1; iter.next(); } output.holderCount = locals.count; } ``` -------------------------------- ### Example of Curly Braces Style Source: https://github.com/qubic/core/blob/main/doc/contributing.md Demonstrates the required style for curly braces in code, where each opening brace starts on a new line. This applies to conditional blocks, loops, functions, and classes. ```cpp if (cond) { // do something } else { // do something else } ``` -------------------------------- ### CMake Static Library Creation and Installation Source: https://github.com/qubic/core/blob/main/lib/platform_os/CMakeLists.txt Defines the source files for the project, creates a static library named 'platform_os', applies OS-specific compiler flags, sets linker language properties, and specifies installation rules for the library. ```cmake # Source files set(SOURCES edk2_debug.c sleep.cpp ) # Create static library add_library(platform_os STATIC ${SOURCES}) # Apply OS-specific compiler flags from the centralized detection module apply_os_compiler_flags(platform_os) # Set library properties set_target_properties(platform_os PROPERTIES LINKER_LANGUAGE CXX ) # Install install(TARGETS platform_os ARCHIVE DESTINATION lib LIBRARY DESTINATION lib ) ``` -------------------------------- ### Bugfix External Tool Example (C++) Source: https://github.com/qubic/core/blob/main/doc/contracts.md An example of an external tool written in C++ that can be used to adjust smart contract state files during an epoch transition for bugfixes. This tool must have publicly available source code. ```cpp // Example C++ external tool for state file adjustment // This is a conceptual example and would need specific implementation details // based on the contract's state structure. #include #include #include int main(int argc, char* argv[]) { if (argc != 3) { std::cerr << "Usage: " << argv[0] << " \n"; return 1; } std::ifstream infile(argv[1], std::ios::binary); std::ofstream outfile(argv[2], std::ios::binary); if (!infile.is_open()) { std::cerr << "Error opening input file: " << argv[1] << std::endl; return 1; } if (!outfile.is_open()) { std::cerr << "Error opening output file: " << argv[2] << std::endl; return 1; } // --- State Adjustment Logic --- // This section would contain the specific logic to read the old state, // modify it (e.g., add new fields, reorder), and write the new state. // For example, reading uint64_t values and writing them back, potentially // with added zero-initialized fields at the end. char buffer[1024]; // Example buffer size while (infile.read(buffer, sizeof(buffer))) { outfile.write(buffer, infile.gcount()); } outfile.write(buffer, infile.gcount()); // Write any remaining bytes // --- Example: Appending new zero-initialized data --- // Assuming new fields need to be added and initialized to zero. // This is highly dependent on the contract's state structure. // For instance, if you are adding 4 new uint64_t fields: // for (int i = 0; i < 4; ++i) { // uint64_t zero_val = 0; // outfile.write(reinterpret_cast(&zero_val), sizeof(zero_val)); // } infile.close(); outfile.close(); std::cout << "State file adjusted successfully." << std::endl; return 0; } ``` -------------------------------- ### Bugfix External Tool Example (Python) Source: https://github.com/qubic/core/blob/main/doc/contracts.md An example of an external tool written in Python that can be used to adjust smart contract state files during an epoch transition for bugfixes. This tool must have publicly available source code. ```python # Example Python external tool for state file adjustment # This is a conceptual example and would need specific implementation details # based on the contract's state structure. import sys import struct def adjust_state(input_file, output_file): try: with open(input_file, 'rb') as infile, open(output_file, 'wb') as outfile: # --- State Adjustment Logic --- # This section would contain the specific logic to read the old state, # modify it (e.g., add new fields, reorder), and write the new state. # For example, reading and writing uint64_t values. chunk_size = 1024 while True: chunk = infile.read(chunk_size) if not chunk: break outfile.write(chunk) # --- Example: Appending new zero-initialized data --- # Assuming new fields need to be added and initialized to zero. # This is highly dependent on the contract's state structure. # For instance, if you are adding 4 new uint64_t fields: # num_new_fields = 4 # for _ in range(num_new_fields): # zero_val = 0 # Represents a zero-initialized uint64_t # outfile.write(struct.pack(' ") sys.exit(1) input_filename = sys.argv[1] output_filename = sys.argv[2] adjust_state(input_filename, output_filename) ``` -------------------------------- ### Project Setup and C++ Standard Configuration Source: https://github.com/qubic/core/blob/main/src/CMakeLists.txt Initializes the CMake project and sets the C++ standard to C++20, which is required by GoogleTest. It also defines include directories for the project and its libraries. ```cmake cmake_minimum_required(VERSION 3.15) project(qubic_core CXX ASM_MASM) # GoogleTest requires at least C++20 set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Include directories include_directories(${CMAKE_CURRENT_SOURCE_DIR}) include_directories(${CMAKE_SOURCE_DIR}/lib/) ``` -------------------------------- ### Configure START_NETWORK_FROM_SCRATCH Flag Source: https://github.com/qubic/core/blob/main/SEAMLESS.md This C preprocessor directive controls how a node initializes at the start of a new epoch. Setting it to 0 allows the node to fetch initial data from peers for seamless transitions, while setting it to 1 forces a restart from a predefined tick. ```c #define START_NETWORK_FROM_SCRATCH 0 ``` ```c #define START_NETWORK_FROM_SCRATCH 1 ``` -------------------------------- ### CMake Project Setup and Standards Source: https://github.com/qubic/core/blob/main/lib/platform_os/CMakeLists.txt Initializes the CMake project, sets the minimum required version, and defines the C++ and C language standards to be used for compilation. Ensures that the specified standards are strictly enforced. ```cmake cmake_minimum_required(VERSION 3.14) project(platform_os CXX C) # Set C++ standard set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Set C standard set(CMAKE_C_STANDARD 11) set(CMAKE_C_STANDARD_REQUIRED ON) ``` -------------------------------- ### C++ Profiling Macros Example Source: https://github.com/qubic/core/blob/main/doc/contributing.md Demonstrates the usage of various profiling macros within a C++ function. These macros help measure the execution time of code blocks and identify specific sections for performance analysis. Ensure ENABLE_PROFILING is defined to activate these macros. ```C++ void processTick() { // measure all of processTick(): PROFILE_SCOPE(); // other code ... // measure code until leaving the scope that is ended with PROFILE_SCOPE_END(); may be also left with return, break etc. PROFILE_NAMED_SCOPE_BEGIN("processTick(): BEGIN_TICK"); contractProcessorPhase = BEGIN_TICK; contractProcessorState = 1; WAIT_WHILE(contractProcessorState); PROFILE_SCOPE_END(); // other code ... if (isMainMode()) { // measure code until scope is left PROFILE_NAMED_SCOPE("processTick(): broadcast custom mining shares tx"); // ... } } ``` -------------------------------- ### Conditional Logic for Epoch Transitions (JavaScript) Source: https://github.com/qubic/core/blob/main/SEAMLESS.md Illustrates conditional logic for handling protocol changes across epochs. This example shows how to implement different data processing behaviors based on the current system epoch, allowing for gradual updates or maintaining backward compatibility. ```javascript if (system.epoch >= 103) { // do something new } else { // Keep processing like the old way } ``` -------------------------------- ### Profiling Features from profiling.h Source: https://github.com/qubic/core/blob/main/doc/contributing.md The `src/platform/profiling.h` header file provides utilities for code profiling, allowing measurement of execution frequency and duration. Specific code examples for its usage are not provided in the source text. ```cpp #include "src/platform/profiling.h" // Example usage would go here, but is not detailed in the provided text. ``` -------------------------------- ### Issue Asset with qpi.issueAsset() Source: https://github.com/qubic/core/blob/main/doc/contracts.md Issues a new asset with a fixed number of shares. The issuer is the public key/ID passed to the function. The asset name has specific formatting requirements (starts with A-Z, followed by A-Z or 0-9, max 7 characters). The issuer initially owns all shares. ```qbic qpi.issueAsset(assetName, numberOfShares) // Example: // qpi.issueAsset("MYASSET", 1000000) ``` -------------------------------- ### CMake Project Setup and C++ Standard Source: https://github.com/qubic/core/blob/main/benchmark_uefi/CMakeLists.txt Initializes the CMake project for C++ and sets the C++ standard to 20, ensuring it's required. This is fundamental for any modern C++ project using CMake. ```cmake cmake_minimum_required(VERSION 3.10) project(M256UefiBenchmark CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) ``` -------------------------------- ### Get Shareholder Proposal Data (C++) Source: https://github.com/qubic/core/blob/main/doc/contracts_proposals.md Defines the GetShareholderProposal user function to retrieve proposal data. It takes a proposal index as input and returns the proposal details along with the proposer's public key. On error, the proposal type in the output is set to 0. ```C++ struct GetShareholderProposal_input { uint16 proposalIndex; }; struct GetShareholderProposal_output { ProposalDataT proposal; id proposerPubicKey; }; PUBLIC_FUNCTION(GetShareholderProposal) { // On error, output.proposal.type is set to 0 output.proposerPubicKey = qpi(state.proposals).proposerId(input.proposalIndex); qpi(state.proposals).getProposal(input.proposalIndex, output.proposal); } ``` -------------------------------- ### Define START_NETWORK_FROM_SCRATCH for Seamless Transition (C) Source: https://github.com/qubic/core/blob/main/SEAMLESS.md Sets the START_NETWORK_FROM_SCRATCH flag to 0 for seamless network transitions. This is used when updating or joining a running network that has not restarted from scratch. The node attempts to fetch initial tick data from peers, requiring a valid previous epoch database and active ticking nodes. ```c #define START_NETWORK_FROM_SCRATCH 0 ``` -------------------------------- ### Partition Disk using gdisk for Qubic Source: https://github.com/qubic/core/blob/main/README.md This bash command sequence uses 'gdisk' to partition a disk, remove existing partitions, create a new partition of up to 200GB, set its type to 'ef00' (EFI System Partition), and save the changes. This is an alternative method for preparing a disk for Qubic. ```bash echo -e "o\nY\nd\nn\n\n\n+200G\n\nt\n\nef00\nw\nY" | gdisk /dev/sda ``` -------------------------------- ### Define START_NETWORK_FROM_SCRATCH for Full Restarts (C) Source: https://github.com/qubic/core/blob/main/SEAMLESS.md Sets the START_NETWORK_FROM_SCRATCH flag to 1 for full network restarts. This is used when initiating a new network or performing a coordinated restart of all nodes. It defines the first tick and timestamp based on `TICK` in `public_settings.h` and a fixed Wednesday 12:00 UTC. ```c #define START_NETWORK_FROM_SCRATCH 1 ``` -------------------------------- ### UEFI Startup Script for Qubic Node Source: https://github.com/qubic/core/blob/main/README.md This batch script configures the UEFI environment for a Qubic node. It sets the timezone to UTC, configures network settings (DHCP or static IP), changes to the boot drive, navigates to the EFI boot directory, and executes the Qubic EFI application. ```batch timezone -s 00:00 ifconfig -s eth0 dhcp fs0: cd efi cd boot Qubic.efi ``` -------------------------------- ### QPI Functions for Contract Procedures Source: https://github.com/qubic/core/blob/main/doc/contracts.md The QpiContextProcedureCall class provides essential QPI functions for user procedures. These include `qpi.transfer()` for moving QUs, `qpi.burn()` for consuming QUs, `qpi.issueAsset()` for creating new assets, and `qpi.transferShareOwnershipAndPossession()` for asset share management. Additionally, `invocator()`, `invocationReward()`, and `originator()` provide crucial context about the procedure's caller and transaction origin. ```c++ qpi.transfer(destination_id, amount); ``` ```c++ qpi.burn(amount); ``` ```c++ qpi.issueAsset(asset_name, total_shares); ``` ```c++ qpi.transferShareOwnershipAndPossession(asset_id, shares_to_transfer, destination_id); ``` ```c++ auto caller_id = qpi.invocator(); ``` ```c++ auto reward = qpi.invocationReward(); ``` ```c++ auto originator_id = qpi.originator(); ``` -------------------------------- ### Unit Test Smart Contracts with Google Test (C++) Source: https://context7.com/qubic/core/llms.txt Demonstrates how to write unit tests for Qubic smart contracts using the Google Test framework in C++. This includes setting up a test fixture, mocking dependencies like the QPI context, and asserting expected outcomes for contract functions such as 'Deposit' and hash map operations. Requires the Google Test library. ```cpp // test/contract_example.cpp #include "gtest/gtest.h" #include "contracts/qpi.h" // Mock QPI context for testing class ContractTest : public ::testing::Test { protected: void SetUp() override { // Initialize test state } }; TEST_F(ContractTest, TestDeposit) { // Setup Deposit_input input; Deposit_output output; // Mock invocation reward mockQpi.setInvocationReward(1000000); mockQpi.setInvocator(testUserId); // Execute CONTRACT::Deposit(mockQpi, state, input, output, locals); // Verify EXPECT_EQ(output.depositedAmount, 1000000); EXPECT_EQ(output.errorCode, SUCCESS); sint64 balance = 0; state.balances.get(testUserId, balance); EXPECT_EQ(balance, 1000000); } TEST_F(ContractTest, TestHashMap) { HashMap map; id key1 = testId1; map.set(key1, 100); EXPECT_TRUE(map.contains(key1)); sint64 value = 0; EXPECT_TRUE(map.get(key1, value)); EXPECT_EQ(value, 100); } ``` -------------------------------- ### Implement Get Shareholder Votes (C++) Source: https://github.com/qubic/core/blob/main/doc/contracts_proposals.md Provides the default implementation for the GetShareholderVotes function. This function retrieves the votes cast by a specific voter or shareholder for a given proposal. On error, the proposal type in the output is set to 0. ```C++ struct GetShareholderVotes_input { id voter; uint16 proposalIndex; }; typedef ProposalMultiVoteDataV1 GetShareholderVotes_output; PUBLIC_FUNCTION(GetShareholderVotes) { // On error, output.votes.proposalType is set to 0 qpi(state.proposals).getVotes(input.proposalIndex, input.voter, output); } ``` -------------------------------- ### Implement Get Shareholder Voting Results (C++) Source: https://github.com/qubic/core/blob/main/doc/contracts_proposals.md Provides the default implementation for the GetShareholderVotingResults function. This function returns the overall voting results for a specific proposal, including total votes authorized. On error, totalVotesAuthorized is set to 0. ```C++ struct GetShareholderVotingResults_input { uint16 proposalIndex; }; typedef ProposalSummarizedVotingDataV1 GetShareholderVotingResults_output; PUBLIC_FUNCTION(GetShareholderVotingResults) { // On error, output.totalVotesAuthorized is set to 0 qpi(state.proposals).getVotingSummary( input.proposalIndex, output); } ``` -------------------------------- ### Get Asset Name from String for Qubic Contracts Source: https://github.com/qubic/core/blob/main/doc/contracts_proposals.md This C++ code snippet demonstrates how to obtain the `uint64` representation of a contract's asset name, which is required for the `DEFINE_SHAREHOLDER_PROPOSAL_STORAGE` macro. The asset name is typically a 7-character string found in `src/contact_core/contract_def.h`. ```C++ std::cout << assetNameFromString("QUTIL") << std::endl; ``` -------------------------------- ### Enable Transaction Add-on Status Request Source: https://github.com/qubic/core/blob/main/test/README.md This directive enables the transaction add-on for monitoring transaction processing status. Setting this define to `1` activates the `moneyflew` service, allowing verification of transaction processing. ```c++ #define ADDON_TX_STATUS_REQUEST 1 ``` -------------------------------- ### Get Shareholder Proposal Indices (C++) Source: https://github.com/qubic/core/blob/main/doc/contracts_proposals.md Implements the GetShareholderProposalIndices contract user function for listing proposals. It can return indices of active proposals or those from prior epochs based on the 'activeProposals' flag. It supports pagination by allowing subsequent calls with the last returned index. ```C++ struct GetShareholderProposalIndices_input { bit activeProposals; // Set true to return indices of active proposals, false for proposals of prior epochs sint32 prevProposalIndex; // Set -1 to start getting indices. If returned index array is full, call again with highest index returned. }; struct GetShareholderProposalIndices_output { uint16 numOfIndices; // Number of valid entries in indices. Call again if it is 64. Array indices; // Requested proposal indices. Valid entries are in range 0 ... (numOfIndices - 1). }; PUBLIC_FUNCTION(GetShareholderProposalIndices) { if (input.activeProposals) { // Return proposals that are open for voting in current epoch // (output is initialized with zeros by contract system) while ((input.prevProposalIndex = qpi(state.proposals).nextProposalIndex(input.prevProposalIndex, qpi.epoch())) >= 0) { output.indices.set(output.numOfIndices, input.prevProposalIndex); ++output.numOfIndices; if (output.numOfIndices == output.indices.capacity()) break; } } else { // Return proposals of previous epochs not overwritten yet // (output is initialized with zeros by contract system) while ((input.prevProposalIndex = qpi(state.proposals).nextFinishedProposalIndex(input.prevProposalIndex)) >= 0) { output.indices.set(output.numOfIndices, input.prevProposalIndex); ++output.numOfIndices; if (output.numOfIndices == output.indices.capacity()) break; } } } ``` -------------------------------- ### Implement Set Shareholder Proposal System Procedure (C++) Source: https://github.com/qubic/core/blob/main/doc/contracts_proposals.md This C++ code implements the SET_SHAREHOLDER_PROPOSAL system procedure. It handles incoming shareholder proposals by copying data from a generic buffer into a custom input structure and then calling the SetShareholderProposal function. The input is a 1024-byte buffer, and the output is a proposal index. ```C++ struct SET_SHAREHOLDER_PROPOSAL_locals { SetShareholderProposal_input userProcInput; }; SET_SHAREHOLDER_PROPOSAL_WITH_LOCALS() { copyFromBuffer(locals.userProcInput, input); CALL(SetShareholderProposal, locals.userProcInput, output); } ``` -------------------------------- ### Enable Tick Data Autosave Mode Source: https://github.com/qubic/core/blob/main/test/README.md This define enables the automatic saving of tick data, allowing the node to reload its state upon resetting. Setting this to `1` activates the autosave mode, which can be triggered manually by pressing F8. ```c++ #define TICK_STORAGE_AUTOSAVE_MODE 1 ``` -------------------------------- ### Implement FinalizeShareholderStateVarProposals in Qubic Contracts Source: https://github.com/qubic/core/blob/main/doc/contracts_proposals.md This C++ snippet shows how to implement the `FinalizeShareholderStateVarProposals` procedure using the `IMPLEMENT_FinalizeShareholderStateVarProposals` QPI macro. This procedure is called within `END_EPOCH` to update state variables based on accepted proposals. The example demonstrates updating various fee-related state variables. ```C++ struct QUTIL { // ... IMPLEMENT_FinalizeShareholderStateVarProposals() { // When you call FinalizeShareholderStateVarProposals(), the following code is run for each // proposal of the current epoch that has been accepted. // // Your code should set the state variable that the proposal is about to the accepted value. // This can be done as in this example taken from QUTIL: switch (input.proposal.variableOptions.variable) { case 0: state.smt1InvocationFee = input.acceptedValue; break; case 1: state.pollCreationFee = input.acceptedValue; break; case 2: state.pollVoteFee = input.acceptedValue; break; case 3: state.distributeQuToShareholderFeePerShareholder = input.acceptedValue; break; case 4: state.shareholderProposalFee = input.acceptedValue; break; } } // ... } ``` -------------------------------- ### Define Input for Pre-Acquire Shares Source: https://github.com/qubic/core/blob/main/doc/contracts.md Defines the input structure for the `PRE_ACQUIRE_SHARES()` system procedure in contract B. This structure contains information about the asset, ownership, number of shares, offered fee, and the index of the other contract involved in the transfer. ```C++ struct PreManagementRightsTransfer_input { Asset asset; id owner; id possessor; sint64 numberOfShares; sint64 offeredFee; uint16 otherContractIndex; }; ``` -------------------------------- ### Define Output for Pre-Acquire Shares Source: https://github.com/qubic/core/blob/main/doc/contracts.md Defines the output structure for the `PRE_ACQUIRE_SHARES()` system procedure in contract B. It includes a boolean `allowTransfer` to indicate acceptance and `requestedFee` which contract A must pay. ```C++ struct PreManagementRightsTransfer_output { bool allowTransfer; sint64 requestedFee; }; ``` -------------------------------- ### DateTime Handling in C++ Source: https://context7.com/qubic/core/llms.txt Provides high-precision date and time operations with microsecond accuracy. Includes methods for setting, getting, validating, adding time, calculating durations, and comparing DateAndTime objects. Also demonstrates usage in time-locked deposits and unlocks. ```cpp // src/contracts/qpi.h struct DateAndTime { void set(uint64 year, uint64 month, uint64 day, uint64 hour, uint64 minute, uint64 second, uint64 millisec = 0, uint64 microsec = 0); uint16 getYear() const; uint8 getMonth() const; uint8 getDay() const; uint8 getHour() const; uint8 getMinute() const; uint8 getSecond() const; bool isValid() const; static bool isLeapYear(uint64 year); bool add(sint64 years, sint64 months, sint64 days, sint64 hours, sint64 minutes, sint64 seconds, sint64 millisecs = 0, sint64 microsecs = 0); bool addDays(sint64 days); uint64 durationMicrosec(const DateAndTime& other) const; uint64 durationDays(const DateAndTime& other) const; bool operator<(const DateAndTime& other) const; bool operator>(const DateAndTime& other) const; }; // Example: Time-locked deposits PUBLIC_PROCEDURE(TimeLock) { DateAndTime unlockTime = qpi.now(); unlockTime.addDays(input.lockDays); LockRecord record; record.owner = qpi.invocator(); record.amount = qpi.invocationReward(); record.unlockTime = unlockTime; state.locks.set(qpi.invocator(), record); } PUBLIC_PROCEDURE(Unlock) { LockRecord record; state.locks.get(qpi.invocator(), record); if (qpi.now() > record.unlockTime && record.amount > 0) { qpi.transfer(qpi.invocator(), record.amount); record.amount = 0; state.locks.set(qpi.invocator(), record); } } ``` -------------------------------- ### Release Asset Management Rights with qpi.releaseShares() Source: https://github.com/qubic/core/blob/main/doc/contracts.md Allows a contract that currently holds asset management rights to release them to another contract. This is a prerequisite for other contracts to manage the ownership and possession of those shares. ```qbic qpi.releaseShares(assetName, targetContractAddress) // Example: // qpi.releaseShares("MYASSET", "0x123...") ``` -------------------------------- ### Implement Shareholder Proposal Fees (C++) Source: https://github.com/qubic/core/blob/main/doc/contracts_proposals.md Implements the GetShareholderProposalFees function to return fees for invoking shareholder proposal and voting procedures. It defines input and output structures and provides a default implementation that assumes no vote fee, but allows for customization. ```C++ typedef NoData GetShareholderProposalFees_input; struct GetShareholderProposalFees_output { sint64 setProposalFee; sint64 setVoteFee; }; PUBLIC_FUNCTION(GetShareholderProposalFees) { output.setProposalFee = setProposalFeeVarOrValue; output.setVoteFee = 0; } ``` -------------------------------- ### Format Disk as FAT32 with QUBIC Label (Linux) Source: https://github.com/qubic/core/blob/main/README.md This bash command formats a specified disk device as FAT32 and sets its label to 'QUBIC'. This is a prerequisite for preparing the Qubic boot device. ```bash # sample command in linux mkfs.fat -F 32 -n QUBIC /dev/sda ``` -------------------------------- ### Array Container: Fixed-size, bounds-checked array in C++ Source: https://context7.com/qubic/core/llms.txt The Array container provides a fixed-size, bounds-checked array. Its capacity must be a power of 2. It supports operations like getting, setting, and comparing ranges of elements. This is useful for managing collections of user data or other fixed-size structures within contracts. ```cpp // src/contracts/qpi.h template struct Array { static inline constexpr uint64 capacity(); inline const T& get(uint64 index) const; inline void set(uint64 index, const T& value); inline void setAll(const T& value); inline void setRange(uint64 indexBegin, uint64 indexEnd, const T& value); inline bool rangeEquals(uint64 indexBegin, uint64 indexEnd, const T& value) const; }; // Example: User balance tracking struct CONTRACT_STATE : public ContractBase { protected: struct UserData { id userId; sint64 balance; uint32 lastActivityEpoch; }; Array users; // Must be power of 2 uint64 userCount; public: PUBLIC_PROCEDURE(Deposit) { UserData userData; userData.userId = qpi.invocator(); userData.balance = qpi.invocationReward(); userData.lastActivityEpoch = qpi.epoch(); state.users.set(state.userCount, userData); state.userCount = state.userCount + 1; } }; ``` -------------------------------- ### CMake Build Configuration for Qubic Core Source: https://github.com/qubic/core/blob/main/CMakeLists.txt This snippet configures the build process for the Qubic Core project using CMake. It sets the minimum CMake version, project name, C++ standard, and includes a custom compiler setup module. Build options for tests, benchmarks, and the EFI application can be toggled. ```cmake cmake_minimum_required(VERSION 3.15) project(qubic CXX) # Set C++ standard set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Include the centralized compiler detection module list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") include(CompilerSetup) # Build options option(BUILD_TESTS "Build the test suite" ON) option(BUILD_BENCHMARK "Build the EFI benchmark application" OFF) option(BUILD_EFI "Build the EFI application" ON) option(USE_SANITIZER "Build test with sanitizer support (clang only)" ON) if(IS_WINDOWS) message(WARNING "Building on Windows using Visual Studio and CMake has undergone limited testing and is not officially supported at this time.") if(USE_SANITIZER) message(WARNING "Building tests with sanitizer support is not supported on Windows.") endif() endif() # Always include platform_common as it's needed for both application and tests add_subdirectory(lib/platform_common) if(BUILD_EFI OR BUILD_BENCHMARK) add_subdirectory(lib/platform_efi) endif() # Build the tests first. On fail, the build will fail completely if(BUILD_TESTS) message(STATUS "--- Test suite ---") enable_testing() add_subdirectory(lib/platform_os) # If we're not building the application, we still need src for tests # but don't make it a default target if(NOT BUILD_EFI) add_subdirectory(src EXCLUDE_FROM_ALL) endif() add_subdirectory(test) endif() # Build the application if requested if(BUILD_EFI) message(STATUS "--- EFI Core application ---") add_subdirectory(src) endif() # Add the UEFI m256i benchmark if(BUILD_BENCHMARK) message(STATUS "-- EFI Benchmark --") add_subdirectory(benchmark_uefi) endif() ```