Unit Noso.General

Description

Unit for general functions.

Uses

Overview

Classes, Interfaces, Objects and Records

Name Description
Record TMultiOrderData Record structure for multi-order data
Packed Record TOrderData Record structure for order data
Class TStreamHelper TStream helper class for string manipulation in streams

Functions and Procedures

function AppFileName(): String;
function CombineTextFiles(FileList: TStringArray; const Destination: String; DeleteSources: Boolean = True): Boolean;
function CreateEmptyFile(const FileName: String): Boolean;
function ExtractMasternodesText(const Text: String): String;
function GetCirculatingSupply(const Block: Integer): Int64;
function GetCommand(const Line: String): String;
function GetCustomFee(const Block: Integer): Int64;
function GetDevPercentage(Block: Integer): Integer;
function GetMasterNodesPercentage(const Block: Integer; const MainnetMode: String = 'NORMAL'): Integer;
function GetMaximumToSend(const Amount: Int64): Int64;
function GetMinimumFeeForAmount(const Amount: Int64): Int64;
function GetParameter(const Line: String; const ParamNumber: Int64; const Delimiter: String = ' '): String;
function GetPoSPercentage(const Block: Integer): Integer;
function GetProtocolCommand(const Line: String): String;
function GetStackRequired(const Block: Integer): Int64;
function HashRateToReadable(const Speed: Int64): String;
function IntToCurrency(const Value: Int64): String;
function IsValidIP(const IpAddress: String): Boolean;
function LoadTextFromDisk(const FileName: TFileName): String;
function OrderToString(const Order: TOrderData): String;
function OSVersion: String;
function RequestLineToPeer(const Host: String; const Port: Integer; const Command: String): String;
function RequestToPeer(const HostAndPort, Command: String): String;
procedure RunExternalProgram(const ProgramToRun: String);
function SaveTextToDisk(const FileName: TFileName; const Text: String): Boolean;
function SendApiRequest(const Url: String): String;
function SendFileViaTCP(const FileName, Message, Host: String; const Port: Integer): Boolean;
function ToNegative(const Number: Int64): Int64;
function TryCopyFile(const Source, Destination: String): Boolean;
function TryDeleteFile(const FileName: String): Boolean;
function UnzipFile(const FileName: String; DeleteFile: Boolean): Boolean;

Types

TBlockOrders = specialize TArray<TOrderData>;
TStringArray = specialize TArray<String>;

Description

Functions and Procedures

function AppFileName(): String;

Returns the name of the application executable without the path.

Example:

var
  AppName: String;
begin
  AppName := AppFileName();
  Writeln('The application file name is: ', AppName);
end;

Returns

The file name of the application executable.

function CombineTextFiles(FileList: TStringArray; const Destination: String; DeleteSources: Boolean = True): Boolean;

Combines multiple text files into one destination file.

Example:

var
  Success: Boolean;
  Files: TStringArray;
begin
  Files := ['file1.txt', 'file2.txt', 'file3.txt'];
  Success := CombineTextFiles(Files, 'combined.txt', True);
  if Success then
    Writeln('Files combined successfully!')
  else
    Writeln('Failed to combine the files.');
end;

Parameters
FileList
An array of file names to combine.
Destination
The destination file where the combined text will be saved.
DeleteSources
If True, the source files will be deleted after they are combined. Defaults to True.
Returns

True if all files were successfully combined and saved, False otherwise.

function CreateEmptyFile(const FileName: String): Boolean;

Creates an empty file on disk.

Example:

var
  Success: Boolean;
begin
  Success := CreateEmptyFile('emptyfile.txt');
  if Success then
    Writeln('Empty file created successfully!')
  else
    Writeln('Failed to create the file.');
end;

Parameters
FileName
The name of the empty file to create.
Returns

True if the file was created successfully, False otherwise.

function ExtractMasternodesText(const Text: String): String;

Extracts the masternode's text in a string.

Parameters
Text
The master node text.
Returns

The substring after the '$' character.

function GetCirculatingSupply(const Block: Integer): Int64;

Calculates the circulating supply of Noso based on the blockchain block number.

Note
This function computes the circulating supply of Noso based on the given block number. The supply follows a specific issuance schedule. The calculation takes into account two phases:

  • From block 0 to 209999 with a supply increase of 5,000,000,000 units per block;

  • From block 210000 onwards with the same supply increase rate.

Parameters
Block
The current block.
Returns

The circulating supply as an Int64 value.

function GetCommand(const Line: String): String;

Extracts the command from the first parameter of the input string.

This function extracts the first parameter from a delimited string and converts it to uppercase.

Parameters
Line
The input string containing delimited parameters.
Returns

The first parameter of the string, converted to uppercase.

function GetCustomFee(const Block: Integer): Int64;

Returns the custom fee.

Parameters
Block
The current block.
Returns

The custom fee as an Int64 value.

function GetDevPercentage(Block: Integer): Integer;

Returns the developer percentage.

Parameters
Block
The current block.
Returns

The developer percentage for the specified block, as a number from 0 to 10000.

function GetMasterNodesPercentage(const Block: Integer; const MainnetMode: String = 'NORMAL'): Integer;

Calculates the percentage of master nodes based on the current block number and mode.

Parameters
Block
The current block number.
MainnetMode
The mode of the mainnet. If it contains 'MNSONLY', the percentage is adjusted for master nodes only. Defaults to 'NORMAL'.
Returns

The percentage of master nodes.

function GetMaximumToSend(const Amount: Int64): Int64;

Returns the maximum amount that can be sent for a specific amount.

Parameters
Amount
The amount.
Returns

The maximum amount.

function GetMinimumFeeForAmount(const Amount: Int64): Int64;

Returns the minimum fee that can be paid for a specific amount.

Parameters
Amount
The amount to which the fee applies.
Returns

The minimum fee.

function GetParameter(const Line: String; const ParamNumber: Int64; const Delimiter: String = ' '): String;

Extracts a specific parameter from a delimited string

Note
This function handles nested parentheses, where text inside parentheses is treated as a single parameter

Parameters
Line
The input string containing delimited parameters
ParamNumber
The number of the parameter to extract (starting from 0)
Delimiter
The character used to separate parameters (default is space)
Returns

The extracted parameter, or an empty string if not found

function GetPoSPercentage(const Block: Integer): Integer;

Returns the PoS percentage.

Parameters
Block
The current block.
Returns

The PoS percentage for the specified block, as a number from 0 to 10000.

function GetProtocolCommand(const Line: String): String;

Extracts the protocol command from the input string.

This function extracts the protocol command from a delimited string and converts it to uppercase.

Parameters
Line
The input string containing delimited parameters.
Returns

The protocol command, converted to uppercase.

function GetStackRequired(const Block: Integer): Int64;

Returns the stack required for Noso.

Parameters
Block
The current block.
Returns

The stack size as an Int64 value.

function HashRateToReadable(const Speed: Int64): String;

Converts an integer hashrate into a human-readable format.

The function formats the hashrate into Gh/s, Mh/s, kh/s, or h/s based on its magnitude.

var
  HashRate: Int64;
begin
  HashRate := 5000000000;
  WriteLn('Hash rate: ', HashRateToReadable(HashRate)); // 5,00 Gh/s

  HashRate := 234000000;
  WriteLn('Hash rate: ', HashRateToReadable(HashRate)); // 234,00 Mh/s

  HashRate := 740000;
  WriteLn('Hash rate: ', HashRateToReadable(HashRate)); // 740,00 Kh/s

  HashRate := 21240;
  WriteLn('Hash rate: ', HashRateToReadable(HashRate)); // 21,24 Kh/s

  HashRate := 240;
  WriteLn('Hash rate: ', HashRateToReadable(HashRate)); // 240 h/s

  HashRate := 56;
  WriteLn('Hash rate: ', HashRateToReadable(HashRate)); // 56 h/s
end.

Parameters
Speed
The hashrate value to be converted.
Returns

A string representing the human-readable hashrate.

function IntToCurrency(const Value: Int64): String;

Converts an integer value to a currency format with two decimal places.

The function formats the value as a string with thousands separators and a decimal point.

var
  Value: Int64;
  FormattedCurrency: String;
begin
  Value := -10230456789;
  FormattedCurrency := IntToCurrency(Value);
  WriteLn('Currency: ', FormattedCurrency); // -102.30456789
end.

Parameters
Value
The integer value to be converted to currency format.
Returns

A string representing the formatted currency value.

function IsValidIP(const IpAddress: String): Boolean;

Validates an IP address.

Note
An IP address is considered valid if it is an IPv4 address (4 values from 0 to 255 separated by dots, e.g. 34.64.210.3) and it isn't in an invalid range like loopback (127.x.x.x) and private networks (192.168.x.x)

if not IsValidIP('127.0.0.1') then
  Writeln('localhost is not valid!');

if not IsValidIP('192.168.100.1') then
  Writeln('Private IP is not valid!');

if IsValidIP('142.250.186.35') then
  Writeln('Google IP is valid!');

Parameters
IpAddress
The IP address to be validated.
Returns

True if the IP address is valid, False otherwise.

function LoadTextFromDisk(const FileName: TFileName): String;

Loads text from a file on disk.

Example:

var
  FileText: String;
begin
  FileText := LoadTextFromDisk('example.txt');
  if FileText <> '' then
    Writeln('File loaded successfully: ', FileText)
  else
    Writeln('Failed to load the file.');
end;

Parameters
FileName
The name and path of the file to load.
Returns

The content of the file as a string, or an empty string in case of failure.

function OrderToString(const Order: TOrderData): String;

Converts an order record to a formatted string.

Example:

var
  OrderString: String;
  MyOrder: TOrderData;
begin
  MyOrder := GetOrder(); // Could be any order.
  Writeln('Order as string: ', OrderToString(MyOrder));
end;

Parameters
Order
The order record to convert.
Returns

A string representing the order.

function OSVersion: String;

Returns the OS name as a string.

function RequestLineToPeer(const Host: String; const Port: Integer; const Command: String): String;

Send a command to peer via TCP and return the response.

Example:

var
  Response: String;
begin
  Response := RequestLineToPeer('192.168.1.100', 8080, 'GET_INFO');
  if Response <> '' then
    WriteLn('Response from peer: ', Response)
  else
    WriteLn('Failed to get a response from peer.');
end;

Parameters
Host
The hostname or IP address of the peer.
Port
The port number of the peer.
Command
The command to be sent to the peer.
Returns

The response from the peer as a string.

function RequestToPeer(const HostAndPort, Command: String): String;

Send a command to a peer using a combined Host:Port string.

Example:

var
  Response: String;
begin
  Response := RequestToPeer('example.com:9000', 'PING');
  if Response <> '' then
    WriteLn('Response from peer: ', Response)
  else
    WriteLn('Failed to get a response from peer.');
end;

Parameters
HostAndPort
The string in the format 'host:port'.
Command
The command to send to the peer.
Returns

The response from the peer as a string.

procedure RunExternalProgram(const ProgramToRun: String);

Runs an external program or script based on the operating system. The procedure handles environment variables and executes the given program or script.

Note
On Unix systems, the program to run should be a script with a proper interpreter (e.g., bash script).

begin
  RunExternalProgram('notepad.exe');
end.

Parameters
ProgramToRun
The path to the executable or script to be run.
function SaveTextToDisk(const FileName: TFileName; const Text: String): Boolean;

Saves a given text to a file on disk.

Example:

var
  Success: Boolean;
begin
  Success := SaveTextToDisk('example.txt', 'This is some example text.');
  if Success then
    Writeln('File saved successfully!')
  else
    Writeln('Failed to save the file.');
end;

Parameters
FileName
The name and path of the file to save.
Text
The content to save to the file.
Returns

True if the file was saved successfully, False otherwise.

function SendApiRequest(const Url: String): String;

Send HTTP GET request to the specified URL.

Example:

var
  ApiResponse: String;
begin
  ApiResponse := SendApiRequest('https://api.example.com/data');
  if ApiResponse <> '' then
    WriteLn('API Response: ', ApiResponse)
  else
    WriteLn('Failed to get a response from the API.');
end;

Parameters
Url
The URL to send the request to.
Returns

The response from the API as a string.

function SendFileViaTCP(const FileName, Message, Host: String; const Port: Integer): Boolean;

Sends a file to a peer via TCP, preceded by a message.

Example:

var
  Success: Boolean;
begin
  Success := SendFileViaTCP('example.txt', 'Sending file', '192.168.1.10', 8080);
  if Success then
    Writeln('File sent successfully!')
  else
    Writeln('Failed to send the file.');
end;

Parameters
FileName
The name of the file to be sent.
Message
The message to be sent before the file.
Host
The hostname or IP address of the peer.
Port
The port number to connect to.
Returns

True if the file was sent successfully, False otherwise.

function ToNegative(const Number: Int64): Int64;

Calculates the negative absolute value of a number.

Note
In essence, this is equivalent to -Abs(Number).

Writeln(ToNegative(-10)); // -10
Writeln(ToNegative(0));   // 0
Writeln(ToNegative(25));  // -25

Parameters
Number
The number.
Returns

The negated number if Number is positive, or Number otherwise.

function TryCopyFile(const Source, Destination: String): Boolean;

Copies a file from source to destination.

Warning
This function will overwrite the destination, if it exists.

Example:

var
  Success: Boolean;
begin
  Success := TryCopyFile('source.txt', 'destination.txt');
  if Success then
    Writeln('File copied successfully!')
  else
    Writeln('Failed to copy the file.');
end;

Parameters
Source
The full path of the source file.
Destination
The full path of the destination file.
Returns

True if the file was copied successfully, False otherwise.

function TryDeleteFile(const FileName: String): Boolean;

Attempts to delete a file safely.

Example:

var
  Success: Boolean;
begin
  Success := TryDeleteFile('example.txt');
  if Success then
    Writeln('File deleted successfully!')
  else
    Writeln('Failed to delete the file.');
end;

Parameters
FileName
The name of the file to delete.
Returns

True if the file was deleted successfully, False otherwise.

function UnzipFile(const FileName: String; DeleteFile: Boolean): Boolean;

Unzips a file and optionally deletes the source file.

Example:

var
  Success: Boolean;
begin
  Success := UnzipFile('archive.zip', True);
  if Success then
    Writeln('File unzipped and deleted successfully!')
  else
    Writeln('Failed to unzip the file.');
end;

Parameters
FileName
The name of the zip file to be extracted.
DeleteFile
If True, deletes the source file after extraction.
Returns

True if the file was unzipped successfully, False otherwise.

Types

TBlockOrders = specialize TArray<TOrderData>;

Dynamic array of TOrderData records

TStringArray = specialize TArray<String>;

Dynamic array of strings


Generated by PasDoc 0.16.0-snapshot.