From d5d03316a703827b92796a750257482aaca925e1 Mon Sep 17 00:00:00 2001 From: Peter Kalambet Date: Fri, 20 Oct 2023 01:12:42 +0200 Subject: [PATCH 1/3] Add comments to the RPC folder --- .../Tests/Runtime/SampleTestsBase.cs | 2 +- src/ChainSafe.Gaming/RPC/Bytes/Bytes.cs | 35 +++- .../Contracts/Builders/ABITypedRegistry.cs | 36 ++++ .../RPC/Contracts/Builders/ContractBuilder.cs | 76 ++++++++ .../DeployContractTransactionBuilder.cs | 45 ++++- .../RPC/Contracts/Builders/EventBuilder.cs | 40 +++- .../Contracts/Builders/EventTopicBuilder.cs | 101 ++++++++++ .../Builders/FilterInput/BlockRange.cs | 50 ++++- .../Builders/FilterInput/FilterExtensions.cs | 60 ++++++ .../FilterInput/FilterInputBuilder.cs | 43 ++++ .../Builders/FilterInput/TopicFilter.cs | 27 +++ .../FilterInput/TopicFilterContainer.cs | 28 +++ .../Contracts/Builders/FilterInputBuilder.cs | 17 ++ .../RPC/Contracts/Builders/FunctionBuilder.cs | 184 +++++++++++++++++- .../Contracts/Builders/FunctionBuilderBase.cs | 66 +++++++ .../RPC/Contracts/Contract.cs | 18 ++ .../RPC/Contracts/ContractBuilderConfig.cs | 35 ++++ .../Contracts/ContractBuilderExtensions.cs | 9 + .../RPC/Contracts/EventLog.cs | 17 ++ .../Contracts/Extensions/EventExtensions.cs | 28 +++ .../RPC/Contracts/IEventLog.cs | 9 + src/ChainSafe.Gaming/RPC/HDNode/HDNode.cs | 34 ++++ .../RPC/HDNode/Wordlists/Wordlist.cs | 20 ++ .../RPC/HDNode/Wordlists/WordlistEnglish.cs | 20 ++ src/ChainSafe.Gaming/RPC/Providers/Event.cs | 58 ++++++ src/ChainSafe.Gaming/RPC/Providers/FeeData.cs | 15 ++ .../RPC/Providers/Formatter.cs | 9 + .../RLP/ConvertorForRLPEncodingExtensions.cs | 58 ++++++ src/ChainSafe.Gaming/RPC/RLP/IRLPElement.cs | 4 + src/ChainSafe.Gaming/RPC/RLP/RLP.cs | 17 +- src/ChainSafe.Gaming/RPC/RLP/RLPCollection.cs | 9 + src/ChainSafe.Gaming/RPC/RLP/RLPItem.cs | 15 ++ .../RPC/RLP/RLPStringFormatter.cs | 9 + .../RPC/SigningKey/SigningKey.cs | 19 ++ .../RPC/Transactions/Formatter.cs | 18 ++ .../RPC/Utils/IsUnityBuild.cs | 3 + src/ChainSafe.Gaming/RPC/Utils/Units.cs | 43 ++++ .../Scripts/Scenes/Login.cs | 65 ++++--- .../Scripts/Utilities/WalletConnectModal.cs | 7 +- 39 files changed, 1299 insertions(+), 50 deletions(-) diff --git a/Packages/io.chainsafe.web3-unity/Tests/Runtime/SampleTestsBase.cs b/Packages/io.chainsafe.web3-unity/Tests/Runtime/SampleTestsBase.cs index 0b741ccb6..a61240dea 100644 --- a/Packages/io.chainsafe.web3-unity/Tests/Runtime/SampleTestsBase.cs +++ b/Packages/io.chainsafe.web3-unity/Tests/Runtime/SampleTestsBase.cs @@ -13,7 +13,7 @@ public class SampleTestsBase { protected Web3 web3Result; - + protected WalletConnectConfig config; [UnitySetUp] diff --git a/src/ChainSafe.Gaming/RPC/Bytes/Bytes.cs b/src/ChainSafe.Gaming/RPC/Bytes/Bytes.cs index c41845bf3..6810fbbcb 100644 --- a/src/ChainSafe.Gaming/RPC/Bytes/Bytes.cs +++ b/src/ChainSafe.Gaming/RPC/Bytes/Bytes.cs @@ -3,13 +3,27 @@ namespace ChainSafe.Gaming.Evm.Bytes { + /// + /// Provides utility functions for manipulating and validating byte arrays and hexadecimal strings. + /// public class Bytes { + /// + /// Converts a byte array into its hexadecimal representation with a "0x" prefix. + /// + /// Byte array to be converted. + /// Hexadecimal representation of the byte array with "0x" prefix. public static string Hexlify(byte[] value) { return "0x" + BitConverter.ToString(value).Replace("-", string.Empty); } + /// + /// Converts a string into its hexadecimal representation with a "0x" prefix. + /// If the string is already in hex format, it is returned as is. + /// + /// String to be converted. + /// Hexadecimal representation of the string with "0x" prefix, or the original string if it's already in hex format. public static string Hexlify(string value) { if (IsHexString(value)) @@ -20,6 +34,13 @@ public static string Hexlify(string value) return "0x" + value; } + /// + /// Pads the provided hexadecimal string with zeros to meet the desired length. + /// + /// Hexadecimal string to be padded. + /// Desired length for the hexadecimal string representation excluding the "0x" prefix. + /// Hexadecimal string padded with zeros to the specified length. + /// Thrown when the provided value is not a valid hex string or if the value's length exceeds the desired length. public static string HexZeroPad(string value, int lenght) { if (!IsHexString(value)) @@ -34,17 +55,28 @@ public static string HexZeroPad(string value, int lenght) while (value.Length < (2 * lenght) + 2) { - value = string.Format("0x0{0}", value.Substring(2)); + value = $"0x0{value.Substring(2)}"; } return value; } + /// + /// Pads the provided byte array with zeros to meet the desired length in its hexadecimal representation. + /// + /// Byte array to be padded. + /// Desired length for the hexadecimal representation excluding the "0x" prefix. + /// Hexadecimal representation of the byte array, padded with zeros to the specified length. public static string HexZeroPad(byte[] value, int lenght) { return HexZeroPad(Hexlify(value), lenght); } + /// + /// Validates if the provided string is a valid hexadecimal string with a "0x" prefix. + /// + /// String to be validated. + /// True if the string is a valid hexadecimal string, otherwise false. public static bool IsHexString(string value) { if (!new Regex("^0x[0-9a-fA-F]*$").IsMatch(value)) @@ -52,7 +84,6 @@ public static bool IsHexString(string value) return false; } - // if (length && value.length !== 2 + 2 * length) { return false; } return true; } } diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/ABITypedRegistry.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/ABITypedRegistry.cs index 6c22d2e5a..5f41e3471 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/ABITypedRegistry.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/ABITypedRegistry.cs @@ -5,6 +5,9 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders { + /// + /// A static class for managing and accessing ABI (Application Binary Interface) types for smart contracts. + /// public static class ABITypedRegistry { private static readonly ConcurrentDictionary FunctionAbiRegistry = new(); @@ -13,11 +16,22 @@ public static class ABITypedRegistry private static readonly AttributesToABIExtractor AbiExtractor = new(); + /// + /// Gets the FunctionABI of type TFunctionMessage. + /// + /// The type of the function message. + /// An object of type FunctionABI. public static FunctionABI GetFunctionABI() { return GetFunctionABI(typeof(TFunctionMessage)); } + /// + /// Gets the FunctionABI for the given type. + /// + /// The type to get the FunctionABI for. + /// An object of type FunctionABI. + /// Thrown when the given type is not a valid FunctionABI type. public static FunctionABI GetFunctionABI(Type functionABIType) { if (!FunctionAbiRegistry.ContainsKey(functionABIType)) @@ -30,11 +44,22 @@ public static FunctionABI GetFunctionABI(Type functionABIType) return FunctionAbiRegistry[functionABIType]; } + /// + /// Gets the EventABI of type TEvent. + /// + /// The type of the event. + /// An object of type EventABI. public static EventABI GetEvent() { return GetEvent(typeof(TEvent)); } + /// + /// Gets the EventABI for the given type. + /// + /// The type to get the EventABI for. + /// An object of type EventABI. + /// Thrown when the given type is not a valid EventABI type. public static EventABI GetEvent(Type type) { if (!EventAbiRegistry.ContainsKey(type)) @@ -47,11 +72,22 @@ public static EventABI GetEvent(Type type) return EventAbiRegistry[type]; } + /// + /// Gets the ErrorABI of type TError. + /// + /// The type of the error. + /// An object of type ErrorABI. public static ErrorABI GetError() { return GetError(typeof(TError)); } + /// + /// Gets the ErrorABI for the given type. + /// + /// The type to get the ErrorABI for. + /// An object of type ErrorABI. + /// Thrown when the given type is not a valid ErrorABI type. public static ErrorABI GetError(Type type) { if (!ErrorAbiRegistry.ContainsKey(type)) diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/ContractBuilder.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/ContractBuilder.cs index c9e5fb5e0..762fd031a 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/ContractBuilder.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/ContractBuilder.cs @@ -8,14 +8,27 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders { + /// + /// Represents a builder pattern class used to build a contract. + /// public class ContractBuilder { + /// + /// Initializes a new instance of the class using ABI string and contract address. + /// + /// ABI string of the contract. + /// Ethereum address of the contract. public ContractBuilder(string abi, string contractAddress) { ContractABI = ABIDeserialiserFactory.DeserialiseContractABI(abi); Address = contractAddress; } + /// + /// Initializes a new instance of the class using a contract message type and contract address. + /// + /// Type containing attributes representing the contract ABI. + /// Ethereum address of the contract. public ContractBuilder(Type contractMessageType, string contractAddress) { var abiExtractor = new AttributesToABIExtractor(); @@ -23,6 +36,11 @@ public ContractBuilder(Type contractMessageType, string contractAddress) Address = contractAddress; } + /// + /// Initializes a new instance of the class using multiple contract message types and contract address. + /// + /// Array of Types containing attributes representing the contract ABI. + /// Ethereum address of the contract. public ContractBuilder(Type[] contractMessagesTypes, string contractAddress) { var abiExtractor = new AttributesToABIExtractor(); @@ -30,15 +48,33 @@ public ContractBuilder(Type[] contractMessagesTypes, string contractAddress) Address = contractAddress; } + /// + /// Gets or sets the ABI of the contract. + /// public ContractABI ContractABI { get; set; } + /// + /// Gets or sets the Ethereum address of the contract. + /// public string Address { get; set; } + /// + /// Retrieves the default filter input for the contract. + /// + /// Starting block for the filter. Optional. + /// Ending block for the filter. Optional. + /// The default filter input for the contract. public NewFilterInput GetDefaultFilterInput(BlockParameter fromBlock = null, BlockParameter toBlock = null) { return FilterInputBuilder.GetDefaultFilterInput(Address, fromBlock, toBlock); } + /// + /// Retrieves the function builder for a specific function using its type. + /// + /// Type of the function. + /// The function builder for the specified function type. + /// Thrown when the specified type lacks a required Function Attribute. public FunctionBuilder GetFunctionBuilder() { var function = FunctionAttribute.GetAttribute() ?? @@ -46,16 +82,32 @@ public FunctionBuilder GetFunctionBuilder() return new FunctionBuilder(Address, GetFunctionAbi(function.Name)); } + /// + /// Retrieves the function builder for a specific function using its name. + /// + /// Name of the function. + /// The function builder for the specified function name. public FunctionBuilder GetFunctionBuilder(string name) { return new FunctionBuilder(Address, GetFunctionAbi(name)); } + /// + /// Retrieves the function builder for a specific function using its signature. + /// + /// Signature of the function. + /// The function builder for the specified function signature. public FunctionBuilder GetFunctionBuilderBySignature(string signature) { return new FunctionBuilder(Address, GetFunctionAbiBySignature(signature)); } + /// + /// Retrieves the error ABI for a specific error using its name. + /// + /// Name of the error. + /// The error ABI for the specified name. + /// Thrown when the Contract ABI is not initialized or the error is not found. public ErrorABI GetErrorAbi(string name) { if (ContractABI == null) @@ -68,6 +120,12 @@ public ErrorABI GetErrorAbi(string name) return errorAbi; } + /// + /// Retrieves the event ABI for a specific event using its name. + /// + /// Name of the event. + /// The event ABI for the specified name. + /// Thrown when the Contract ABI is not initialized or the event is not found. public EventABI GetEventAbi(string name) { if (ContractABI == null) @@ -80,6 +138,12 @@ public EventABI GetEventAbi(string name) return eventAbi; } + /// + /// Retrieves the event ABI for a specific event using its signature. + /// + /// Signature of the event. + /// The event ABI for the specified signature. + /// Thrown when the Contract ABI is not initialized or the event signature is not found. public EventABI GetEventAbiBySignature(string signature) { if (ContractABI == null) @@ -96,6 +160,12 @@ public EventABI GetEventAbiBySignature(string signature) return eventAbi; } + /// + /// Retrieves the function ABI for a specific function using its name. + /// + /// Name of the function. + /// The function ABI for the specified name. + /// Thrown when the Contract ABI is not initialized or the function is not found. public FunctionABI GetFunctionAbi(string name) { if (ContractABI == null) @@ -108,6 +178,12 @@ public FunctionABI GetFunctionAbi(string name) return functionAbi; } + /// + /// Retrieves the function ABI for a specific function using its signature. + /// + /// Signature of the function. + /// The function ABI for the specified signature. + /// Thrown when the Contract ABI is not initialized or the function signature is not found. public FunctionABI GetFunctionAbiBySignature(string signature) { if (ContractABI == null) diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/DeployContractTransactionBuilder.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/DeployContractTransactionBuilder.cs index f05526fa2..263f767c0 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/DeployContractTransactionBuilder.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/DeployContractTransactionBuilder.cs @@ -5,26 +5,54 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders { + /// + /// A class for building deployment transactions for Ethereum contracts. + /// public class DeployContractTransactionBuilder { private readonly ConstructorCallEncoder constructorCallEncoder = new(); + /// + /// Ensures the given contract bytecode does not contain any placeholders. + /// + /// The contract bytecode to check. public static void EnsureByteCodeDoesNotContainPlaceholders(string byteCode) { ByteCodeLibraryLinker.EnsureDoesNotContainPlaceholders(byteCode); } + /// + /// Gets the encoded data for deploying a contract. + /// + /// The contract's bytecode. + /// The contract's ABI. + /// The constructor's parameter values. + /// The encoded data. public string GetData(string contractByteCode, string abi, params object[] values) { var contract = ABIDeserialiserFactory.DeserialiseContractABI(abi); return constructorCallEncoder.EncodeRequest(contractByteCode, contract.Constructor.InputParameters, values); } + /// + /// Gets the encoded data for deploying a contract. + /// + /// The type of the constructor parameters. + /// The contract's bytecode. + /// The constructor's parameters. + /// The encoded data. public string GetData(string contractByteCode, TConstructorParams inputParams) { return constructorCallEncoder.EncodeRequest(inputParams, contractByteCode); } + /// + /// Builds the encoded data. + /// + /// The contract's bytecode. + /// The contract's ABI. + /// The constructor's parameter values. + /// The encoded data. private string BuildEncodedData(string contractByteCode, string abi, object[] values) { EnsureByteCodeDoesNotContainPlaceholders(contractByteCode); @@ -46,6 +74,13 @@ private string BuildEncodedData(string contractByteCode, string abi, object[] va return encodedData; } + /// + /// Builds a transaction request for deploying a contract. + /// + /// The contract's bytecode. + /// The contract's ABI. + /// The constructor's parameter values. + /// The transaction request. public TransactionRequest BuildTransaction( string contractByteCode, string abi, @@ -58,6 +93,14 @@ public TransactionRequest BuildTransaction( }; } + /// + /// Builds a transaction request for deploying a contract. + /// + /// The type of the constructor parameters. + /// The contract's bytecode. + /// The sender's Ethereum address. + /// The constructor's parameters. + /// The transaction request. public TransactionRequest BuildTransaction( string contractByteCode, string from, @@ -70,4 +113,4 @@ public TransactionRequest BuildTransaction( }; } } -} \ No newline at end of file +} diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/EventBuilder.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/EventBuilder.cs index 6df624dd4..3c5983770 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/EventBuilder.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/EventBuilder.cs @@ -8,19 +8,40 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders { + /// + /// Class that creates and manipulates events on an Ethereum contract. + /// This class is obsolete and it's recommended to use the EventABI extensions instead. + /// [Obsolete("Use the EventABI extensions instead")] public class EventBuilder { + /// + /// Initializes a new instance of the class. + /// + /// The Ethereum contract address. + /// The event ABI of the Ethereum contract. public EventBuilder(string contractAddress, EventABI eventAbi) { ContractAddress = contractAddress; EventABI = eventAbi; } + /// + /// Gets or sets the address of the Ethereum contract. + /// public string ContractAddress { get; set; } + /// + /// Gets the EventABI instance related to the Ethereum contract. + /// public EventABI EventABI { get; } + /// + /// Decodes all events for a given type. + /// + /// The type of the event. + /// The logs for an event on an Ethereum contract. + /// A list of decoded events. public static List> DecodeAllEvents(FilterLog[] logs) where T : new() { @@ -72,6 +93,11 @@ public NewFilterInput CreateFilterInput( return EventABI.CreateFilterInput(ContractAddress, filterTopic1, filterTopic2, filterTopic3, fromBlock, toBlock); } + /// + /// Checks if the log is related to the specific event. + /// + /// The log to check. + /// true if the log is for the event, false otherwise. public bool IsLogForEvent(JToken log) { return EventABI.IsLogForEvent(log); @@ -92,16 +118,28 @@ public FilterLog[] GetLogsForEvent(JArray logs) return EventABI.GetLogsForEvent(logs); } + /// + /// Decodes all events for a specific event. + /// + /// The type of the event. + /// The logs for an event on an Ethereum contract. + /// A list of decoded events. public List> DecodeAllEventsForEvent(FilterLog[] logs) where T : new() { return EventABI.DecodeAllEvents(logs); } + /// + /// Decodes all events for a specific event. + /// + /// The type of the event. + /// The logs (in JArray format) for an event on an Ethereum contract. + /// A list of decoded events. public List> DecodeAllEventsForEvent(JArray logs) where T : new() { return EventABI.DecodeAllEvents(logs); } } -} \ No newline at end of file +} diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/EventTopicBuilder.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/EventTopicBuilder.cs index c5a2b706e..197de910d 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/EventTopicBuilder.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/EventTopicBuilder.cs @@ -5,10 +5,18 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders { + /// + /// Event topic builder. Using this class you can build the topics for a given event. + /// public class EventTopicBuilder { private readonly EventABI eventABI; + /// + /// Initializes a new instance of the class. + /// Constructor for the EventTopicBuilder class. + /// + /// ABI of the event. public EventTopicBuilder(EventABI eventABI) { this.eventABI = eventABI; @@ -19,16 +27,28 @@ private static string EnsureHexPrefix(string input) return input.EnsureHexPrefix(); } + /// + /// Returns the event signature topic as the only topic. + /// + /// Object array with the event signature topic. public object[] GetSignatureTopicAsTheOnlyTopic() { return new object[] { GetSignatureTopic() }; } + /// + /// Returns the event signature topic. + /// + /// Object that represents the event signature topic. public object GetSignatureTopic() { return eventABI.Sha3Signature.EnsureHexPrefix(); } + /// + /// Gets the event topics using first the provided topic. + /// + /// Object array representing the event topics. public object[] GetTopics(object[] firstTopic) { if (eventABI.IsAnonymous) @@ -39,6 +59,10 @@ public object[] GetTopics(object[] firstTopic) return new[] { GetSignatureTopic(), GetValueTopic(firstTopic, 1) }; } + /// + /// Gets the event topics using the provided first and second topics. + /// + /// Object array representing the event topics. public object[] GetTopics(object[] firstTopic, object[] secondTopic) { if (eventABI.IsAnonymous) @@ -49,6 +73,10 @@ public object[] GetTopics(object[] firstTopic, object[] secondTopic) return new[] { GetSignatureTopic(), GetValueTopic(firstTopic, 1), GetValueTopic(secondTopic, 2) }; } + /// + /// Gets the event topics using the provided first, second, and third topics. + /// + /// Object array representing the event topics. public object[] GetTopics(object[] firstTopic, object[] secondTopic, object[] thirdTopic) { if (eventABI.IsAnonymous) @@ -67,26 +95,58 @@ public object[] GetTopics(object[] firstTopic, object[] secondTopic, object[] th }; } + /// + /// Gets the event topics using the provided first topics. + /// + /// First topic. + /// Object array representing the event topics. public object[] GetTopics(object firstTopic) { return GetTopics(new[] { firstTopic }); } + /// + /// Gets the event topics using the provided first and second topics. + /// + /// First topic. + /// Second topic. + /// Object array representing the event topics. public object[] GetTopics(object firstTopic, object secondTopic) { return GetTopics(new[] { firstTopic }, new[] { secondTopic }); } + /// + /// Gets the event topics using the provided first, second, and third topics. + /// + /// First topic. + /// Second topic. + /// Third topic. + /// Object array representing the event topics. public object[] GetTopics(object firstTopic, object secondTopic, object thirdTopic) { return GetTopics(new[] { firstTopic }, new[] { secondTopic }, new[] { thirdTopic }); } + /// + /// Returns topics for the given first using generic types. + /// + /// First topic. + /// Generic type of the first topic. + /// Object array representing the event topics. public object[] GetTopics(T1 firstTopic) { return GetTopics(firstTopic == null ? null : new[] { (object)firstTopic }); } + /// + /// Returns topics for the given first and second topics using generic types. + /// + /// First topic. + /// Second topic. + /// Generic type of the first topic. + /// Generic type of the second topic. + /// Object array representing the event topics. public object[] GetTopics(T1 firstTopic, T2 secondTopic) { return GetTopics( @@ -94,6 +154,16 @@ public object[] GetTopics(T1 firstTopic, T2 secondTopic) secondTopic == null ? null : new[] { (object)secondTopic }); } + /// + /// Returns topics for the given first, second and third topics using generic types. + /// + /// First topic. + /// Second topic. + /// third topic. + /// Generic type of the first topic. + /// Generic type of the second topic. + /// Generic type of the third topic. + /// Object array representing the event topics. public object[] GetTopics(T1 firstTopic, T2 secondTopic, T3 thirdTopic) { return GetTopics( @@ -102,21 +172,52 @@ public object[] GetTopics(T1 firstTopic, T2 secondTopic, T3 thirdTop thirdTopic == null ? null : new[] { (object)thirdTopic }); } + /// + /// Gets the event topics using the provided first topics. + /// + /// First topic. + /// Generic type of the first topic. + /// Object array representing the event topics. public object[] GetTopics(T1[] firstOrTopics) { return GetTopics(firstOrTopics.Cast().ToArray()); } + /// + /// Gets the event topics using the provided first and second topics. + /// + /// First topic. + /// Second topic. + /// Generic type of the first topic. + /// Generic type of the second topic. + /// Object array representing the event topics. public object[] GetTopics(T1[] firstOrTopics, T2[] secondOrTopics) { return GetTopics(firstOrTopics.Cast().ToArray(), secondOrTopics.Cast().ToArray()); } + /// + /// Gets the event topics using the provided first, second, and third topics. + /// + /// First topic. + /// Second topic. + /// Third topic. + /// Generic type of the first topic. + /// Generic type of the second topic. + /// Generic type of the third topic. + /// Object array representing the event topics. public object[] GetTopics(T1[] firstOrTopics, T2[] secondOrTopics, T3[] thirdOrTopics) { return GetTopics(firstOrTopics.Cast().ToArray(), secondOrTopics.Cast().ToArray(), thirdOrTopics.Cast().ToArray()); } + /// + /// Gets the value topic for the given values and parameter number. + /// + /// Array of values. + /// Number of the parameter. + /// Array of objects representing the value topic. + /// Exception thrown when the event parameter is not found. public object[] GetValueTopic(object[] values, int paramNumber) { if (values == null) diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/BlockRange.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/BlockRange.cs index c2877c50e..b3f033938 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/BlockRange.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/BlockRange.cs @@ -4,21 +4,39 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders.FilterInput { + /// + /// Provides functionality to build and manage Ethereum contracts based on the ABI and address. + /// public readonly struct BlockRange : IEquatable { private readonly int hashCode; + /// + /// Initializes a new instance of the struct. + /// + /// Starting block number. + /// Ending block number. public BlockRange(ulong from, ulong to) : this(new BigInteger(from), new BigInteger(to)) { } + /// + /// Initializes a new instance of the struct. + /// + /// Starting block represented as . + /// Ending block represented as . public BlockRange(BigInteger from, BigInteger to) : this(new HexBigInteger(from), new HexBigInteger(to)) { } + /// + /// Initializes a new instance of the struct. + /// + /// Starting block represented as . + /// Ending block represented as . public BlockRange(HexBigInteger from, HexBigInteger to) { From = from ?? throw new ArgumentNullException(nameof(from)); @@ -27,28 +45,50 @@ public BlockRange(HexBigInteger from, HexBigInteger to) hashCode = new { From, To }.GetHashCode(); } + /// + /// Gets the starting block. + /// public HexBigInteger From { get; } + /// + /// Gets the ending block. + /// public HexBigInteger To { get; } + /// + /// Gets the total number of blocks represented in the range. + /// public BigInteger BlockCount { get; } + /// + /// Equality operator. + /// public static bool operator ==(BlockRange left, BlockRange right) { return left.Equals(right); } + /// + /// Inequality operator. + /// public static bool operator !=(BlockRange left, BlockRange right) { return !(left == right); } + /// + /// Checks equality with other . + /// + /// Return true if equal. public bool Equals(BlockRange other) { - return From.Value.Equals(other.From.Value) && - To.Value.Equals(other.To.Value); + return From.Value.Equals(other.From.Value) && To.Value.Equals(other.To.Value); } + /// + /// Checks equality with given object. + /// + /// Return true if equal. public override bool Equals(object obj) { if (obj is BlockRange other) @@ -59,9 +99,13 @@ public override bool Equals(object obj) return false; } + /// + /// Gets the struct hash code. + /// + /// Hash code value. public override int GetHashCode() { return hashCode; } } -} \ No newline at end of file +} diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/FilterExtensions.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/FilterExtensions.cs index ad19058ef..f437ef37b 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/FilterExtensions.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/FilterExtensions.cs @@ -7,8 +7,16 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders.FilterInput { + /// + /// A class that provides extension methods for Filters. + /// public static class FilterExtensions { + /// + /// Returns a key which can be used to identify the FilterLog. + /// + /// The filter log instance. + /// The key as a string. public static string Key(this FilterLog log) { if (log.TransactionHash == null || log.LogIndex == null) @@ -19,6 +27,12 @@ public static string Key(this FilterLog log) return $"{log.TransactionHash}{log.LogIndex.HexValue}"; } + /// + /// Merges a list of FilterLogs into a master dictionary. + /// + /// The master dictionary of FilterLogs. + /// Array of candidate FilterLogs to be added to the master dictionary. + /// The updated master dictionary. public static Dictionary Merge(this Dictionary masterList, FilterLog[] candidates) { foreach (var log in candidates) @@ -34,6 +48,11 @@ public static Dictionary Merge(this Dictionary + /// Returns the number of blocks in the Filterlog. + /// + /// The NewFilterInput instance. + /// The number of blocks as BigInteger. public static BigInteger? NumberOfBlocksInBlockParameters(this NewFilterInput filter) { if (filter.FromBlock?.BlockNumber == null || filter.ToBlock?.BlockNumber == null) @@ -44,36 +63,77 @@ public static Dictionary Merge(this Dictionary + /// Sets the block range. + /// + /// The NewFilterInput instance. + /// The BlockRange instance. public static void SetBlockRange(this NewFilterInput filter, BlockRange range) => SetBlockRange(filter, range.From, range.To); + /// + /// Sets the block range from a pair of BigIntegers. + /// + /// The NewFilterInput instance. + /// The from block bound. + /// The to block bound. public static void SetBlockRange(this NewFilterInput filter, BigInteger from, BigInteger to) => SetBlockRange(filter, from.ToHexBigInteger(), to.ToHexBigInteger()); + /// + /// Sets the block range from a pair of HexBigIntegers. + /// + /// The NewFilterInput instance. + /// The from block bound as HexBigInteger. + /// The to block bound as HexBigInteger. public static void SetBlockRange(this NewFilterInput filter, HexBigInteger from, HexBigInteger to) { filter.FromBlock = new BlockParameter(from); filter.ToBlock = new BlockParameter(to); } + /// + /// Returns if the Filter is Topic filtered or not. + /// + /// The NewFilterInput instance. + /// The topicNumber to check. + /// True if the TopicNumber exists, otherwise False. public static bool IsTopicFiltered(this NewFilterInput filter, uint topicNumber) { var filterValue = filter.GetFirstTopicValue(topicNumber); return filterValue != null; } + /// + /// Returns first filter value as string. + /// + /// The NewFilterInput instance. + /// The topicNumber to check. + /// The first filter value as string. Null if it doesn't exist. public static string GetFirstTopicValueAsString(this NewFilterInput filter, uint topicNumber) { var filterValue = filter.GetFirstTopicValue(topicNumber); return filterValue?.ToString(); } + /// + /// Returns first filter value. + /// + /// The NewFilterInput instance. + /// The topicNumber to check. + /// The first filter value as object. Null if it doesn't exist. public static object GetFirstTopicValue(this NewFilterInput filter, uint topicNumber) { var topicValues = filter.GetTopicValues(topicNumber); return topicValues.FirstOrDefault(); } + /// + /// Returns filter values as an array for the provided topicNumber. + /// + /// The NewFilterInput instance. + /// The topicNumber for which values are to be fetched. + /// An array of objects representing the filter values. public static object[] GetTopicValues(this NewFilterInput filter, uint topicNumber) { var allTopics = filter.Topics; diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/FilterInputBuilder.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/FilterInputBuilder.cs index 36e15ae85..309866496 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/FilterInputBuilder.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/FilterInputBuilder.cs @@ -22,12 +22,22 @@ public class FilterInputBuilder private readonly EventABI eventAbi; private readonly TopicFilterContainer topics; + /// + /// Initializes a new instance of the class with the given event DTO type. + /// public FilterInputBuilder() { eventAbi = ABITypedRegistry.GetEvent(); topics = new TopicFilterContainer(); } + /// + /// Adds topics to the filter. + /// + /// The property to select. + /// The values of the property to select. + /// A FilterInputBuilder of the modified filter. + /// Generic type parameter of the property. public FilterInputBuilder AddTopic( Expression> propertySelector, IEnumerable desiredValues) { @@ -39,6 +49,13 @@ public FilterInputBuilder AddTopic( return this; } + /// + /// Adds a topic to the filter. + /// + /// The property to select. + /// The value of the property to select. + /// A FilterInputBuilder of the modified filter. + /// Generic type parameter of the property. public FilterInputBuilder AddTopic( Expression> propertySelector, TPropertyType desiredValue) { @@ -52,16 +69,35 @@ public FilterInputBuilder AddTopic( return this; } + /// + /// Builds a filter based on a contract address and block range. + /// + /// The contract address. + /// The block range. + /// A NewFitlerInput with the specified filter settings. public NewFilterInput Build(string contractAddress, BlockRange? blockRange = null) { return Build(new[] { contractAddress }, blockRange); } + /// + /// Builds a filter based on a contract address and block parameter values. + /// + /// The contract address. + /// The 'from' block parameter. + /// The 'to' block parameter. + /// A NewFilterInput with the specified filter settings. public NewFilterInput Build(string contractAddress, BlockParameter from, BlockParameter to) { return Build(new[] { contractAddress }, from, to); } + /// + /// Builds a filter based on multiple contract addresses and/or a block range. + /// + /// The array of contract addresses. + /// The block range. + /// A NewFilterInput with the specified filter settings. public NewFilterInput Build(string[] contractAddresses = null, BlockRange? blockRange = null) { BlockParameter from = blockRange == null ? null : new BlockParameter(blockRange.Value.From); @@ -70,6 +106,13 @@ public NewFilterInput Build(string[] contractAddresses = null, BlockRange? block return Build(contractAddresses, from, to); } + /// + /// Builds a filter based on contract addresses and block parameter values. + /// + /// The array of contract addresses. + /// The 'from' block parameter. + /// The 'to' block parameter. + /// A NewFilterInput with the specified filter settings. public NewFilterInput Build(string[] contractAddresses, BlockParameter from, BlockParameter to) { if (topics.Empty) diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/TopicFilter.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/TopicFilter.cs index 6d0ebe5ef..a12428eb9 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/TopicFilter.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/TopicFilter.cs @@ -4,27 +4,54 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders.FilterInput { + /// + /// Defines a TopicFilter class that is used to filter topic events. + /// internal class TopicFilter { + /// + /// Represents an empty TopicFilter object. + /// internal static readonly TopicFilter Empty = new(null, null); private List values; + /// + /// Initializes a new instance of the class. + /// + /// This property holds event data transfer object. + /// This holds the parameter attribute values. internal TopicFilter(PropertyInfo eventDtoProperty, ParameterAttribute parameterAttribute) { EventDtoProperty = eventDtoProperty; ParameterAttribute = parameterAttribute; } + /// + /// Gets event data transfer object property. + /// + /// Returns the property info of event data transfer object. public PropertyInfo EventDtoProperty { get; } + /// + /// Gets parameter attribute. + /// + /// Returns the parameter attribute. public ParameterAttribute ParameterAttribute { get; } + /// + /// Returns an array of values. + /// + /// Returns an array of values if there are any, or null otherwise. public object[] GetValues() { return values == null || values.Count == 0 ? null : values.ToArray(); } + /// + /// Adds a value to the values list. + /// + /// This object value to add to the list. public void AddValue(object val) { values ??= new List(); diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/TopicFilterContainer.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/TopicFilterContainer.cs index 4a045bed3..61421dded 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/TopicFilterContainer.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInput/TopicFilterContainer.cs @@ -5,9 +5,16 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders.FilterInput { + /// + /// A container for handling Topic filters. + /// + /// A class type. internal class TopicFilterContainer where T : class { + /// + /// Initializes a new instance of the class. + /// internal TopicFilterContainer() { var indexedParameters = PropertiesExtractor @@ -26,16 +33,37 @@ internal TopicFilterContainer() Topics = new[] { Topic1, Topic2, Topic3 }; } + /// + /// Gets a boolean value indicating if TopicFilterContainer is empty. + /// public bool Empty { get; private set; } + /// + /// Gets the first TopicFilter object. + /// public TopicFilter Topic1 { get; private set; } + /// + /// Gets the second TopicFilter object. + /// public TopicFilter Topic2 { get; private set; } + /// + /// Gets the third TopicFilter object. + /// public TopicFilter Topic3 { get; private set; } + /// + /// Private set for Topics array. + /// private TopicFilter[] Topics { get; set; } + /// + /// Returns the TopicFilter object associated with the given PropertyInfo. + /// + /// The PropertyInfo object to match with a TopicFilter object. + /// The TopicFilter object that matches the provided PropertyInfo. + /// Throws an exception if a matching TopicFilter can't be found. public TopicFilter GetTopic(PropertyInfo pInfo) { return diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInputBuilder.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInputBuilder.cs index b88ddc1f9..92541d88e 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInputBuilder.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FilterInputBuilder.cs @@ -2,8 +2,18 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders { + /// + /// Helps in the construction of new FilterInput objects with default parameters set. + /// public class FilterInputBuilder { + /// + /// Constructs a new FilterInput with default parameters set and given 'address', 'fromBlock', and 'toBlock'. + /// + /// A string representing a Ethereum blockchain address. + /// A block parameter object representing the block to start filtering from. Defaults to null. + /// A block parameter object representing the block until which to perform the filter. Defaults to null. + /// Returns a NewFilterInput object with address, fromBlock, and toBlock set. public static NewFilterInput GetDefaultFilterInput(string address, BlockParameter fromBlock = null, BlockParameter toBlock = null) { string[] addresses = null; @@ -15,6 +25,13 @@ public static NewFilterInput GetDefaultFilterInput(string address, BlockParamete return GetDefaultFilterInput(addresses, fromBlock, toBlock); } + /// + /// Constructs a new FilterInput with default parameters set and given array of 'addresses', 'fromBlock', and 'toBlock'. + /// + /// An array of strings, each representing an Ethereum blockchain address. + /// A block parameter object representing the block to start filtering from. Defaults to null. + /// A block parameter object representing the block until which to perform the filter. Defaults to null. + /// Returns a NewFilterInput object with address, fromBlock, and toBlock set. public static NewFilterInput GetDefaultFilterInput(string[] addresses, BlockParameter fromBlock = null, BlockParameter toBlock = null) { var ethFilterInput = new NewFilterInput diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FunctionBuilder.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FunctionBuilder.cs index 59290dc84..a3fd6f495 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FunctionBuilder.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FunctionBuilder.cs @@ -6,19 +6,40 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders { - public class FunctionBuilder : FunctionBuilderBase + /// + /// Main builder for function commands. + /// + public class FunctionBuilder : Nethereum.Contracts.FunctionBuilderBase { + /// + /// Initializes a new instance of the class. + /// + /// The contract address. + /// The function of the ABI. public FunctionBuilder(string contractAddress, FunctionABI function) : base(contractAddress, function) { } + /// + /// Create call input with function inputs. + /// + /// The call input parameters. + /// An instance of CallInput class. public CallInput CreateCallInput(params object[] functionInput) { var encodedInput = GetData(functionInput); return base.CreateCallInput(encodedInput); } + /// + /// Create call input with given parameters. + /// + /// Transaction sender address. + /// Amount of gas allocated for this specific call. + /// Amount of WEI to send with the transaction. + /// Input parameters for the function call. + /// An instance of CallInput class. public CallInput CreateCallInput( string from, HexBigInteger gas, @@ -29,18 +50,37 @@ public CallInput CreateCallInput( return base.CreateCallInput(encodedInput, from, gas, value); } + /// + /// Encodes the function call using the input parameters. + /// + /// Input parameters for the function call. + /// String representation of the encoded function call. public string GetData(params object[] functionInput) { return FunctionCallEncoder.EncodeRequest( FunctionABI.Sha3Signature, FunctionABI.InputParameters, functionInput); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Outgoing transaction sender address. + /// Array of objects that represent function input parameters. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput(string from, params object[] functionInput) { var encodedInput = GetData(functionInput); return base.CreateTransactionInput(encodedInput, from, null, null); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Outgoing transaction sender address. + /// Amount of gas allocated for this specific call. + /// Value in native currency to send. + /// Array of objects that represent function input parameters. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput( string from, HexBigInteger gas, @@ -51,6 +91,15 @@ public TransactionInput CreateTransactionInput( return base.CreateTransactionInput(encodedInput, from, gas, value); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Outgoing transaction sender address. + /// Amount of gas allocated for this specific call. + /// Estimated gas price in WEI. + /// Value in native currency to send. + /// Array of objects that represent function input parameters. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput( string from, HexBigInteger gas, @@ -62,6 +111,17 @@ public TransactionInput CreateTransactionInput( return base.CreateTransactionInput(encodedInput, from, gas, gasPrice, value); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Hex representation of the transaction type. + /// Outgoing transaction sender address. + /// Amount of gas allocated for this specific call. + /// Value in native currency to send. + /// Maximum fee per gas (EIP-1559). + /// Maximum priority fee per gas (EIP-1559). + /// Array of objects that represent function input parameters. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput( HexBigInteger type, string from, @@ -75,6 +135,16 @@ public TransactionInput CreateTransactionInput( return CreateTransactionInput(type, encodedInput, from, gas, value, maxFeePerGas, maxPriorityFeePerGas); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Outgoing transaction sender address. + /// Amount of gas allocated for this specific call. + /// Value in native currency to send. + /// Maximum fee per gas (EIP-1559). + /// Maximum priority fee per gas (EIP-1559). + /// Array of objects that represent function input parameters. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput( string from, HexBigInteger gas, @@ -87,6 +157,12 @@ public TransactionInput CreateTransactionInput( return CreateTransactionInput(TransactionType.EIP1559.AsHexBigInteger(), encodedInput, from, gas, value, maxFeePerGas, maxPriorityFeePerGas); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Another transaction input to copy values from. + /// Array of objects that represent function input parameters. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput(TransactionInput input, params object[] functionInput) { var encodedInput = GetData(functionInput); @@ -94,30 +170,60 @@ public TransactionInput CreateTransactionInput(TransactionInput input, params ob } } - public class FunctionBuilder : FunctionBuilderBase + /// + /// Generic version of . + /// + /// Parametrisation of the function input. + public class FunctionBuilder : Nethereum.Contracts.FunctionBuilderBase { - public FunctionBuilder(string contractAddres) - : base(contractAddres) + /// + /// Initializes a new instance of the class. + /// + /// The contract address. + public FunctionBuilder(string contractAddress) + : base(contractAddress) { FunctionABI = ABITypedRegistry.GetFunctionABI(); } + /// + /// Initializes a new instance of the class. + /// + /// The contract address. + /// The function of the ABI. public FunctionBuilder(string contractAddress, FunctionABI function) : base(contractAddress, function) { } + /// + /// Create call input with parameterless function input. + /// + /// An instance of CallInput class. public CallInput CreateCallInputParameterless() { return CreateCallInput(FunctionCallEncoder.EncodeRequest(FunctionABI.Sha3Signature)); } + /// + /// Create call input with parameterized function input. + /// + /// The call input parameters. + /// An instance of CallInput class. public CallInput CreateCallInput(TFunctionInput functionInput) { var encodedInput = GetData(functionInput); return CreateCallInput(encodedInput); } + /// + /// Create call input with parameterized function input. + /// + /// The call input parameters. + /// Transaction sender address. + /// Amount of gas allocated for this specific call. + /// Amount of WEI to send with the transaction. + /// An instance of CallInput class. public CallInput CreateCallInput( TFunctionInput functionInput, string from, @@ -128,32 +234,68 @@ public CallInput CreateCallInput( return CreateCallInput(encodedInput, from, gas, value); } + /// + /// Encodes the function call using parameterized input parameters as a string. + /// + /// Input parameters for the function call. + /// String representation of the encoded function call. public string GetData(TFunctionInput functionInput) { return FunctionCallEncoder.EncodeRequest(functionInput, FunctionABI.Sha3Signature); } + /// + /// Encodes the function call using parameterized input parameters as a byte array. + /// + /// Input parameters for the function call. + /// Encoded function call as a byte array. public byte[] GetDataAsBytes(TFunctionInput functionInput) { return GetData(functionInput).HexToByteArray(); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Input parameters for the function call. + /// Transaction input to merge with. + /// Object that is ready to be passed to the signer and transaction executor. public TFunctionInput DecodeFunctionInput(TFunctionInput functionInput, TransactionInput transactionInput) { - return FunctionCallDecoder.DecodeFunctionInput(functionInput, FunctionABI.Sha3Signature, transactionInput.Data); + return FunctionCallDecoder.DecodeFunctionInput(functionInput, FunctionABI.Sha3Signature, transactionInput.Data); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Input parameters for the function call. + /// Data that needs to be parsed. + /// Object that is ready to be passed to the signer and transaction executor. public TFunctionInput DecodeFunctionInput(TFunctionInput functionInput, string data) { - return FunctionCallDecoder.DecodeFunctionInput(functionInput, FunctionABI.Sha3Signature, data); + return FunctionCallDecoder.DecodeFunctionInput(functionInput, FunctionABI.Sha3Signature, data); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Input parameters for the function call. + /// Outgoing transaction sender address. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput(TFunctionInput functionInput, string from) { var encodedInput = GetData(functionInput); return CreateTransactionInput(encodedInput, from); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Input parameters for the function call. + /// Outgoing transaction sender address. + /// Amount of gas allocated for this specific call. + /// Value in native currency to send. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput( TFunctionInput functionInput, string from, @@ -164,6 +306,15 @@ public TransactionInput CreateTransactionInput( return CreateTransactionInput(encodedInput, from, gas, value); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Input parameters for the function call. + /// Outgoing transaction sender address. + /// Amount of gas allocated for this specific call. + /// Estimated gas price in WEI. + /// Value in native currency to send. + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput( TFunctionInput functionInput, string from, @@ -175,6 +326,17 @@ public TransactionInput CreateTransactionInput( return CreateTransactionInput(encodedInput, from, gas, gasPrice, value); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Input parameters for the function call. + /// Hex representation of the transaction type. + /// Outgoing transaction sender address. + /// Amount of gas allocated for this specific call. + /// Value in native currency to send. + /// Maximum fee per gas (EIP-1559). + /// Maximum priority fee per gas (EIP-1559). + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput( TFunctionInput functionInput, HexBigInteger type, @@ -188,6 +350,16 @@ public TransactionInput CreateTransactionInput( return CreateTransactionInput(type, encodedInput, from, gas, value, maxFeePerGas, maxPriorityFeePerGas); } + /// + /// Encodes function input parameters and creates a transaction input. + /// + /// Input parameters for the function call. + /// Outgoing transaction sender address. + /// Amount of gas allocated for this specific call. + /// Value in native currency to send. + /// Maximum fee per gas (EIP-1559). + /// Maximum priority fee per gas (EIP-1559). + /// Object that is ready to be passed to the signer and transaction executor. public TransactionInput CreateTransactionInput( TFunctionInput functionInput, string from, diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FunctionBuilderBase.cs b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FunctionBuilderBase.cs index a920b548f..a02505501 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Builders/FunctionBuilderBase.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Builders/FunctionBuilderBase.cs @@ -9,14 +9,21 @@ namespace ChainSafe.Gaming.Evm.Contracts.Builders { + /// Represents a Function Builder Base. public abstract class FunctionBuilderBase { + /// + /// Initializes a new instance of the class with function ABI. + /// protected FunctionBuilderBase(string contractAddress, FunctionABI functionAbi) : this(contractAddress) { FunctionABI = functionAbi; } + /// + /// Initializes a new instance of the class. + /// protected FunctionBuilderBase(string contractAddress) { ContractAddress = contractAddress; @@ -24,12 +31,24 @@ protected FunctionBuilderBase(string contractAddress) FunctionCallEncoder = new FunctionCallEncoder(); } + /// + /// SetUp and get ContractAddress. + /// public string ContractAddress { get; set; } + /// + /// SetUp and get FunctionCallDecoder. + /// protected FunctionCallDecoder FunctionCallDecoder { get; set; } + /// + /// SetUp and get FunctionCallEncoder. + /// protected FunctionCallEncoder FunctionCallEncoder { get; set; } + /// + /// SetUp and get FunctionABI. + /// public FunctionABI FunctionABI { get; protected set; } private static Parameter GetFirstParameterOrNull(Parameter[] parameters) @@ -47,39 +66,68 @@ private static Parameter GetFirstParameterOrNull(Parameter[] parameters) return parameters[0]; } + /// + /// Checks if Transaction Input Data is for Function. + /// + /// True if Transaction Input Data is meant for Function. public bool IsTransactionInputDataForFunction(string data) { return FunctionCallDecoder.IsDataForFunction(FunctionABI, data); } + /// + /// Decode provided string data. + /// + /// List of function output parameters. public List DecodeInput(string data) { return FunctionCallDecoder.DecodeFunctionInput( FunctionABI.Sha3Signature, data, FunctionABI.InputParameters); } + /// + /// Converts stringified JSON to Object Input parameters. + /// + /// Array of object input parameters ready to be used in a function call. public object[] ConvertJsonToObjectInputParameters(string json) { var jObject = JObject.Parse(json); return jObject.ConvertToFunctionInputParameterValues(FunctionABI); } + /// + /// Converts JSON to Object Input Parameters array. + /// + /// Array of object input parameters ready to be used in a function call. public object[] ConvertJsonToObjectInputParameters(JObject jObject) { return jObject.ConvertToFunctionInputParameterValues(FunctionABI); } + /// + /// Decode output stringify data to JObject. + /// + /// Resulted JObject. public JObject DecodeOutputToJObject(string data) { return DecodeOutput(data).ConvertToJObject(); } + /// + /// Decode stingified output data to List of parameters. + /// + /// List of parameters. public List DecodeOutput(string data) { return FunctionCallDecoder.DecodeDefaultData( data, FunctionABI.OutputParameters); } + /// + /// Decode type output based on provided generic type. + /// + /// Output casted to provided generic type. + /// Type of output. public TReturn DecodeTypeOutput(string output) { var function = FunctionOutputAttribute.GetAttribute(); @@ -95,17 +143,31 @@ public TReturn DecodeTypeOutput(string output) } } + /// + /// Decode DTO type output. + /// + /// Output casted to provided generic type. + /// Type of output. public TReturn DecodeDTOTypeOutput(TReturn functionOuput, string output) { return FunctionCallDecoder.DecodeFunctionOutput(functionOuput, output); } + /// + /// Decode DTO type output. + /// + /// Output casted to provided generic type. + /// Type of output. public TReturn DecodeDTOTypeOutput(string output) where TReturn : new() { return FunctionCallDecoder.DecodeFunctionOutput(output); } + /// + /// Creates Transaction Input. + /// + /// Constructed transaction input object. public TransactionInput CreateTransactionInput( string from, HexBigInteger gas, @@ -115,6 +177,10 @@ public TransactionInput CreateTransactionInput( return new TransactionInput(encodedInput, from, gas, value); } + /// + /// Creates Transaction Input. + /// + /// Constructed transaction input object. public TransactionInput CreateTransactionInput( HexBigInteger type, string from, diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Contract.cs b/src/ChainSafe.Gaming/RPC/Contracts/Contract.cs index dd59bf616..e694619b1 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Contract.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Contract.cs @@ -9,6 +9,9 @@ namespace ChainSafe.Gaming.Evm.Contracts { + /// + /// Representation of a contract. + /// public class Contract { private readonly string abi; @@ -18,6 +21,14 @@ public class Contract private readonly Builders.ContractBuilder contractBuilder; private readonly ITransactionExecutor transactionExecutor; + /// + /// Initializes a new instance of the class. + /// + /// The abi. + /// The contract address. + /// The RPC provider. + /// The signer. + /// Transaction executor. internal Contract(string abi, string address, IRpcProvider provider = null, ISigner signer = null, ITransactionExecutor transactionExecutor = null) { if (string.IsNullOrEmpty(abi)) @@ -50,6 +61,13 @@ public Contract Attach(string address) return new Contract(abi, address, provider, signer, transactionExecutor); } + /// + /// Call the contract method. + /// + /// The method to call. + /// The parameters for the method. + /// To overwrite a transaction request. + /// The result of calling the method. public async Task Call(string method, object[] parameters = null, TransactionRequest overwrite = null) { if (string.IsNullOrEmpty(address)) diff --git a/src/ChainSafe.Gaming/RPC/Contracts/ContractBuilderConfig.cs b/src/ChainSafe.Gaming/RPC/Contracts/ContractBuilderConfig.cs index 946e755b9..448ae568f 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/ContractBuilderConfig.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/ContractBuilderConfig.cs @@ -4,14 +4,31 @@ namespace ChainSafe.Gaming.Evm.Contracts { + /// + /// Defines the class. + /// public class ContractBuilderConfig { + /// + /// Initializes a new instance of the class. + /// Prevents a default instance of the class from being created. + /// internal ContractBuilderConfig() { } + /// + /// Gets an internal list of registered contracts. + /// internal List RegisteredContracts { get; } = new List(); + /// + /// Registers a new contract. + /// + /// Name of the contract. + /// The Application Binary Interface (ABI) for the contract. + /// The address of the contract. + /// Returns an instance of the ContractBuilderConfig class. public ContractBuilderConfig RegisterContract(string name, string abi, string address) { RegisteredContracts.Add(new ContractData(name, abi, address)); @@ -19,8 +36,17 @@ public ContractBuilderConfig RegisterContract(string name, string abi, string ad } } + /// + /// Defines the class. + /// internal class ContractData { + /// + /// Initializes a new instance of the class. + /// + /// Name of the contract. + /// The Application Binary Interface (ABI) for the contract. + /// The address of the contract. public ContractData(string name, string abi, string address) { Name = name; @@ -28,10 +54,19 @@ public ContractData(string name, string abi, string address) Address = address; } + /// + /// Gets the name of the contract. + /// public string Name { get; } + /// + /// Gets the Application Binary Interface (ABI) for the contract. + /// public string Abi { get; } + /// + /// Gets the address of the contract. + /// public string Address { get; } } } diff --git a/src/ChainSafe.Gaming/RPC/Contracts/ContractBuilderExtensions.cs b/src/ChainSafe.Gaming/RPC/Contracts/ContractBuilderExtensions.cs index 8fa30d505..2f9303472 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/ContractBuilderExtensions.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/ContractBuilderExtensions.cs @@ -7,8 +7,17 @@ namespace ChainSafe.Gaming.Evm.Contracts { + /// + /// Extension methods for the . + /// public static class ContractBuilderExtensions { + /// + /// Registers and configures contracts. + /// + /// The IWeb3ServiceCollection instance. + /// An action used to configure the ContractBuilderConfig. + /// The IWeb3ServiceCollection instance that method was invoked on. This return value can be used to chain multiple calls for a fluent configuration syntax. public static IWeb3ServiceCollection ConfigureRegisteredContracts(this IWeb3ServiceCollection services, Action configure) { ContractBuilderConfig config = diff --git a/src/ChainSafe.Gaming/RPC/Contracts/EventLog.cs b/src/ChainSafe.Gaming/RPC/Contracts/EventLog.cs index 95f702497..314fede8c 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/EventLog.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/EventLog.cs @@ -2,16 +2,33 @@ namespace ChainSafe.Gaming.Evm.Contracts { + /// + /// Class that defines properties of an Event log. + /// + /// Event type. public class EventLog : IEventLog { + /// + /// Initializes a new instance of the class. + /// + /// The event object of type defined by type parameter T. + /// The log of type FilterLog. public EventLog(T eventObject, FilterLog log) { Event = eventObject; Log = log; } + /// + /// Gets the event of type defined by type parameter T. + /// + /// Returns the event object. public T Event { get; } + /// + /// Gets the log of type FilterLog. + /// + /// Returns the log object. public FilterLog Log { get; } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/RPC/Contracts/Extensions/EventExtensions.cs b/src/ChainSafe.Gaming/RPC/Contracts/Extensions/EventExtensions.cs index 38d8dd988..d57be3416 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/Extensions/EventExtensions.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/Extensions/EventExtensions.cs @@ -14,26 +14,54 @@ namespace ChainSafe.Gaming.Evm.Contracts.Extensions { + /// + /// Class that provides extension methods to events. + /// public static class EventExtensions { + /// + /// Checks if log is for the given event type. + /// + /// Event type. + /// JSON representation of the log. + /// True if log is for the given event, false otherwise. public static bool IsLogForEvent(this JToken log) { var eventABI = ABITypedRegistry.GetEvent(); return eventABI.IsLogForEvent(log); } + /// + /// Checks if log is for the given event type. + /// + /// Event type. + /// Log to check. + /// True if log is for the given event, false otherwise. public static bool IsLogForEvent(this FilterLog log) { var eventABI = ABITypedRegistry.GetEvent(); return eventABI.IsLogForEvent(log); } + /// + /// Checks if filter input is for the given contract address and event type. + /// + /// Event type. + /// Contract address. + /// Filter input to check. + /// True if filter input is for the given contract address and event, false otherwise. public static bool IsFilterInputForEvent(string contractAddress, NewFilterInput filterInput) { var eventABI = ABITypedRegistry.GetEvent(); return eventABI.IsFilterInputForEvent(contractAddress, filterInput); } + /// + /// Checks if log is for this event ABI. + /// + /// Event ABI. + /// JSON representation of the log. + /// True if log is for this event ABI, false otherwise. public static bool IsLogForEvent(this EventABI eventABI, JToken log) { return IsLogForEvent(eventABI, JsonConvert.DeserializeObject(log.ToString())); diff --git a/src/ChainSafe.Gaming/RPC/Contracts/IEventLog.cs b/src/ChainSafe.Gaming/RPC/Contracts/IEventLog.cs index f892a658f..a4b058511 100644 --- a/src/ChainSafe.Gaming/RPC/Contracts/IEventLog.cs +++ b/src/ChainSafe.Gaming/RPC/Contracts/IEventLog.cs @@ -2,8 +2,17 @@ namespace ChainSafe.Gaming.Evm.Contracts { + /// + /// Defining interface for Event logs. + /// public interface IEventLog { + /// + /// Represents a property of FilterLog. + /// + /// + /// A FilterLog object. + /// FilterLog Log { get; } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/RPC/HDNode/HDNode.cs b/src/ChainSafe.Gaming/RPC/HDNode/HDNode.cs index 121970862..0016a82d0 100644 --- a/src/ChainSafe.Gaming/RPC/HDNode/HDNode.cs +++ b/src/ChainSafe.Gaming/RPC/HDNode/HDNode.cs @@ -10,6 +10,9 @@ namespace ChainSafe.Gaming.Evm.HDNode { + /// + /// A Hierarchical deterministic (HD) wallet implementation node. + /// public class HDNode { // private const uint HardenedBit = 0x80000000; @@ -28,6 +31,15 @@ public class HDNode // private readonly int _depth; private readonly ExtKey extKey; + /// + /// Initializes a new instance of the class. + /// Private constructor to enforce that HDNode objects are only created via the static methods. + /// Throws an Exception if the constructor was called directly. + /// + /// An internal sentinel object to ensure the constructor was only called from another HDNode method. + /// Extended key. + /// Mnemonic phrase for the HDNode. + /// String representing the HD path of the node being created. public HDNode(object constructorGuard, ExtKey key, string mnemonic, string path) { if (constructorGuard != HDNode.ConstructorGuard) @@ -41,8 +53,19 @@ public HDNode(object constructorGuard, ExtKey key, string mnemonic, string path) extKey = key; } + /// + /// Gets the private key of this HDNode. + /// + /// Returns the private key of this HDNode. public Key PrivateKey => extKey.PrivateKey; + /// + /// Create a HDNode from mnemonic seed words. Default HD wallet path "m/44'/60'/0'/0". + /// + /// Seed words for wallet. + /// Optional password to protect seed. + /// Locale of seed words. Default is English ('en'). + /// Returns a HDNode. public static HDNode FromMnemonic(string mnemonic, string password = null, string locale = "en") { return FromSeed(MnemonicToSeed(mnemonic, password), mnemonic, "m/44'/60'/0'/0", locale); @@ -64,6 +87,12 @@ public static byte[] MnemonicToSeed(string mnemonic, string password) return new Rfc2898DeriveBytes(pass, salt, 1000).GetBytes(64); } + /// + /// Create a HDNode from entropy seed. + /// + /// Seed entropy. + /// Locale of seed words. Default is English ('en'). + /// Returns a mnemonic string. public static string EntropyToMnemonic(byte[] entropy, string locale = "en") { var wordlist = GetWordlist(locale); @@ -123,6 +152,11 @@ private static Wordlists.Wordlist GetWordlist(string locale) }; } + /// + /// Derive a new HDNode from the path. + /// + /// The path to derive. + /// Returns a new HDNode derived from path. public HDNode DerivePath(string path) { var keyPath = new KeyPath(path); diff --git a/src/ChainSafe.Gaming/RPC/HDNode/Wordlists/Wordlist.cs b/src/ChainSafe.Gaming/RPC/HDNode/Wordlists/Wordlist.cs index bb9b83934..b0693542d 100644 --- a/src/ChainSafe.Gaming/RPC/HDNode/Wordlists/Wordlist.cs +++ b/src/ChainSafe.Gaming/RPC/HDNode/Wordlists/Wordlist.cs @@ -1,16 +1,36 @@ namespace ChainSafe.Gaming.Evm.HDNode.Wordlists { + /// + /// Base class to represent a wordlist. + /// public abstract class Wordlist { + /// + /// Initializes a new instance of the class. + /// + /// local to set. protected Wordlist(string local) { Local = local; } + /// + /// Gets the locale for this wordlist. + /// public string Local { get; } + /// + /// Get word from word index. + /// + /// Index to get word from. + /// Word at the provided index. public abstract string GetWord(int index); + /// + /// Get index from the provided word in the wordlist. + /// + /// Word to get index for. + /// The index of the provided word. public abstract int GetWordIndex(string word); } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/RPC/HDNode/Wordlists/WordlistEnglish.cs b/src/ChainSafe.Gaming/RPC/HDNode/Wordlists/WordlistEnglish.cs index c653d7ab8..32ae28ad3 100644 --- a/src/ChainSafe.Gaming/RPC/HDNode/Wordlists/WordlistEnglish.cs +++ b/src/ChainSafe.Gaming/RPC/HDNode/Wordlists/WordlistEnglish.cs @@ -3,18 +3,28 @@ namespace ChainSafe.Gaming.Evm.HDNode.Wordlists { + /// + /// Represents a word list in English for a Hierarchical Deterministic Wallet (HD Wallet). + /// public class WordlistEnglish : Wordlist { private const string Words = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo"; + // Array where the words are going to be stored, separated and sorted. private string[] wordlist; + /// + /// Initializes a new instance of the class. + /// public WordlistEnglish() : base("en") { } + /// + /// Loads the words into the word list from the Words string if they have not been loaded before. + /// private void LoadWords() { if (wordlist != null && wordlist.Length > 0) @@ -27,12 +37,22 @@ private void LoadWords() // TODO: verify BIP39 wordlist } + /// + /// Returns the word at the specified index. + /// + /// The index at which the word is located. + /// The word at the specified index. public override string GetWord(int index) { LoadWords(); return wordlist[index]; } + /// + /// Returns the index of a specified word. + /// + /// The word to locate in the word list. + /// The zero-based index of the word if it is found, or -1 if it is not. public override int GetWordIndex(string word) { LoadWords(); diff --git a/src/ChainSafe.Gaming/RPC/Providers/Event.cs b/src/ChainSafe.Gaming/RPC/Providers/Event.cs index c0f478b8e..5865069d4 100644 --- a/src/ChainSafe.Gaming/RPC/Providers/Event.cs +++ b/src/ChainSafe.Gaming/RPC/Providers/Event.cs @@ -4,6 +4,9 @@ namespace ChainSafe.Gaming.Evm.Providers { + /// + /// Abstract public class representing an event. + /// public abstract class Event { private readonly List pollableEvents = new() @@ -14,18 +17,35 @@ public abstract class Event "poll", }; + /// + /// Initializes a new instance of the class. + /// + /// Event tag, a string. + /// Event execution constraint, a bool. public Event(string tag, bool once) { Once = once; Tag = tag; } + /// + /// To check if event occurs once. + /// public bool Once { get; set; } + /// + /// Event tag. + /// public string Tag { get; set; } + /// + /// Event type derived from event tag. + /// public string Type => Tag.Substring(0, Tag.IndexOf(":")); + /// + /// Event hash. + /// public string Hash { get @@ -35,6 +55,9 @@ public string Hash } } + /// + /// Probe if the event is pollable or not. + /// public bool IsPollable => Tag.IndexOf(":", StringComparison.Ordinal) >= 0 || pollableEvents.IndexOf(Tag) >= 0; /* @@ -50,35 +73,70 @@ public string _Event() } */ + /// + /// Method to apply the event. + /// + /// Arguments to be used while applying/calling the event. public abstract void Apply(object[] args); } + /// + /// Public class for single-parametric Event instruction. + /// + /// Type that defines the event. public class Event : Event { private readonly Func listener; + /// + /// Initializes a new instance of the class. + /// Constructor for Event class with single parameter. + /// + /// Event tag, a string. + /// Function to be called. + /// Event execution constraint, a bool. public Event(string tag, Func listener, bool once) : base(tag, once) { this.listener = listener; } + /// + /// Method to apply the event. + /// + /// Arguments to be used while applying/calling the event. public override void Apply(object[] args) { listener((T)args[0]); } } + /// + /// Public class for double-parametric Event instruction. + /// + /// First type that defines the event. + /// Second type that defines the event. public class Event : Event { private readonly Func listener; + /// + /// Initializes a new instance of the class. + /// Constructor for Event class with two parameters. + /// + /// Event tag, a string. + /// Function to be called with two arguments. + /// Event execution constraint, a bool. public Event(string tag, Func listener, bool once) : base(tag, once) { this.listener = listener; } + /// + /// Method to apply the event. + /// + /// Arguments to be used while applying/calling the event. public override void Apply(object[] args) { listener((T1)args[0], (T2)args[1]); diff --git a/src/ChainSafe.Gaming/RPC/Providers/FeeData.cs b/src/ChainSafe.Gaming/RPC/Providers/FeeData.cs index bb504c020..3bc2138a3 100644 --- a/src/ChainSafe.Gaming/RPC/Providers/FeeData.cs +++ b/src/ChainSafe.Gaming/RPC/Providers/FeeData.cs @@ -2,14 +2,29 @@ namespace ChainSafe.Gaming.Evm.Providers { + /// + /// Represents fee relevant data in the Ethereum network. + /// public class FeeData { + /// + /// Gets or sets the base fee per gas. + /// public BigInteger BaseFeePerGas { get; set; } + /// + /// Gets or sets the maximum fee per gas that the sender is willing to pay. + /// public BigInteger MaxFeePerGas { get; set; } + /// + /// Gets or sets the maximum fee per gas to be given to the miner. + /// public BigInteger MaxPriorityFeePerGas { get; set; } + /// + /// Gets or sets the price of gas. + /// public BigInteger GasPrice { get; set; } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/RPC/Providers/Formatter.cs b/src/ChainSafe.Gaming/RPC/Providers/Formatter.cs index 1c08cccff..db1ed7142 100644 --- a/src/ChainSafe.Gaming/RPC/Providers/Formatter.cs +++ b/src/ChainSafe.Gaming/RPC/Providers/Formatter.cs @@ -1,7 +1,16 @@ namespace ChainSafe.Gaming.Evm.Providers { + /// + /// Provides functionalities related to formatting operations. + /// public class Formatter { + /// + /// Creates and gets an instance of Transactions.Formatter class. + /// + /// + /// A Transactions.Formatter class instance. + /// public Transactions.Formatter Transaction { get; } = new Transactions.Formatter(); } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/RPC/RLP/ConvertorForRLPEncodingExtensions.cs b/src/ChainSafe.Gaming/RPC/RLP/ConvertorForRLPEncodingExtensions.cs index a5eda48cb..974d1763a 100644 --- a/src/ChainSafe.Gaming/RPC/RLP/ConvertorForRLPEncodingExtensions.cs +++ b/src/ChainSafe.Gaming/RPC/RLP/ConvertorForRLPEncodingExtensions.cs @@ -6,8 +6,16 @@ namespace ChainSafe.Gaming.Evm.RLP { + /// + /// Provides set of static methods for the conversion operations required for RLP (Recursive Length Prefix) encoding . + /// public static class ConvertorForRLPEncodingExtensions { + /// + /// Converts RLP-decoded bytes to BigInteger. + /// + /// Input byte array. + /// Returns BigInteger converted from the input byte array. public static BigInteger ToBigIntegerFromRLPDecoded(this byte[] bytes) { if (bytes == null) @@ -26,26 +34,51 @@ public static BigInteger ToBigIntegerFromRLPDecoded(this byte[] bytes) return new BigInteger(bytes); } + /// + /// Converts a BigInteger to bytes ready for RLP encoding. + /// + /// Input BigInteger. + /// Returns an array of bytes converted from the BigInteger. public static byte[] ToBytesForRLPEncoding(this BigInteger bigInteger) { return ToBytesFromNumber(bigInteger.ToByteArray()); } + /// + /// Converts a integer to bytes ready for RLP encoding. + /// + /// Input integer. + /// Returns an array of bytes converted from the integer. public static byte[] ToBytesForRLPEncoding(this int number) { return ToBytesFromNumber(BitConverter.GetBytes(number)); } + /// + /// Converts a long to bytes ready for RLP encoding. + /// + /// Input long. + /// Returns an array of bytes converted from the long. public static byte[] ToBytesForRLPEncoding(this long number) { return ToBytesFromNumber(BitConverter.GetBytes(number)); } + /// + /// Converts a string to bytes ready for RLP encoding. + /// + /// Input string. + /// Returns an array of bytes converted from the string. public static byte[] ToBytesForRLPEncoding(this string str) { return Encoding.UTF8.GetBytes(str); } + /// + /// Converts a string array to an array of bytes ready for RLP encoding. + /// + /// Input strings array. + /// Returns an array of array of bytes converted from the strings array. public static byte[][] ToBytesForRLPEncoding(this string[] strings) { var output = new List(); @@ -57,16 +90,31 @@ public static byte[][] ToBytesForRLPEncoding(this string[] strings) return output.ToArray(); } + /// + /// Converts a bytes array to integer. + /// + /// Input bytes array. + /// Returns an integer converted from the bytes array. public static int ToIntFromRLPDecoded(this byte[] bytes) { return (int)ToBigIntegerFromRLPDecoded(bytes); } + /// + /// Converts a bytes array to long. + /// + /// Input bytes array. + /// Returns long converted from the bytes array. public static long ToLongFromRLPDecoded(this byte[] bytes) { return (long)ToBigIntegerFromRLPDecoded(bytes); } + /// + /// Converts a bytes array to string. + /// + /// Input bytes array. + /// Returns string converted from the bytes array. public static string ToStringFromRLPDecoded(this byte[] bytes) { if (bytes == null) @@ -77,6 +125,11 @@ public static string ToStringFromRLPDecoded(this byte[] bytes) return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } + /// + /// Converts a bytes array that represents a number to a bytes array that represents the same number but with respect to Little Endian. + /// + /// Input bytes array. + /// Returns bytes array converted from the bytes array. public static byte[] ToBytesFromNumber(byte[] bytes) { if (BitConverter.IsLittleEndian) @@ -87,6 +140,11 @@ public static byte[] ToBytesFromNumber(byte[] bytes) return TrimZeroBytes(bytes); } + /// + /// Removes zero bytes from the beginning of the input bytes array. + /// + /// Input bytes array. + /// New bytes array without zero bytes at the beginning. public static byte[] TrimZeroBytes(this byte[] bytes) { var trimmed = new List(); diff --git a/src/ChainSafe.Gaming/RPC/RLP/IRLPElement.cs b/src/ChainSafe.Gaming/RPC/RLP/IRLPElement.cs index 7614f6bc8..62f52a2a3 100644 --- a/src/ChainSafe.Gaming/RPC/RLP/IRLPElement.cs +++ b/src/ChainSafe.Gaming/RPC/RLP/IRLPElement.cs @@ -5,6 +5,10 @@ namespace ChainSafe.Gaming.Evm.RLP /// public interface IRLPElement { + /// + /// Gets the RLP data. + /// + /// The RLP data. byte[] RLPData { get; } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/RPC/RLP/RLP.cs b/src/ChainSafe.Gaming/RPC/RLP/RLP.cs index dd3f6ca33..813321ae9 100644 --- a/src/ChainSafe.Gaming/RPC/RLP/RLP.cs +++ b/src/ChainSafe.Gaming/RPC/RLP/RLP.cs @@ -96,6 +96,11 @@ public class RLP public static readonly byte[] EmptyByteArray = Array.Empty(); public static readonly byte[] ZeroByteArray = { 0 }; + /// + /// Converts a byte array to an integer. + /// + /// Byte array to be converted. + /// The converted integer. public static int ByteArrayToInt(byte[] bytes) { if (BitConverter.IsLittleEndian) @@ -106,6 +111,11 @@ public static int ByteArrayToInt(byte[] bytes) return BitConverter.ToInt32(bytes, 0); } + /// + /// Decodes a given byte array. + /// + /// Byte array to decode. + /// The decoded RLP element. public static IRLPElement Decode(byte[] msgData) { var rlpCollection = new RLPCollection(); @@ -113,6 +123,11 @@ public static IRLPElement Decode(byte[] msgData) return rlpCollection[0]; } + /// + /// Decodes a collection from a byte array. + /// + /// Byte array to decode. + /// The decoded RLP collection. public static IRLPElement DecodeCollection(byte[] msgData) { var rlpCollection = new RLPCollection(); @@ -121,7 +136,7 @@ public static IRLPElement DecodeCollection(byte[] msgData) } /// - /// Decodes a message from a starting point to an end point. + /// Decodes a message from a starting point to an end point. /// public static void Decode( byte[] msgData, diff --git a/src/ChainSafe.Gaming/RPC/RLP/RLPCollection.cs b/src/ChainSafe.Gaming/RPC/RLP/RLPCollection.cs index 7f5a00d9b..b6b9e963c 100644 --- a/src/ChainSafe.Gaming/RPC/RLP/RLPCollection.cs +++ b/src/ChainSafe.Gaming/RPC/RLP/RLPCollection.cs @@ -2,8 +2,17 @@ namespace ChainSafe.Gaming.Evm.RLP { + /// + /// Defines a Run-Length-Prefix (RLP) Collection. + /// public class RLPCollection : List, IRLPElement { + /// + /// Gets or sets the RLP data. + /// + /// + /// A byte array containing the RLP data. + /// public byte[] RLPData { get; set; } } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/RPC/RLP/RLPItem.cs b/src/ChainSafe.Gaming/RPC/RLP/RLPItem.cs index 43a0f7572..dfb5c823f 100644 --- a/src/ChainSafe.Gaming/RPC/RLP/RLPItem.cs +++ b/src/ChainSafe.Gaming/RPC/RLP/RLPItem.cs @@ -1,16 +1,31 @@ namespace ChainSafe.Gaming.Evm.RLP { + /// + /// Represents an Item that conforms to the Recursive Length Prefix (RLP) encoding scheme. + /// public class RLPItem : IRLPElement { private readonly byte[] rlpData; + /// + /// Initializes a new instance of the class with the provided data. + /// + /// The data to be encoded by RLP. public RLPItem(byte[] rlpData) { this.rlpData = rlpData; } + /// + /// Gets the RLP encoded data. + /// + /// The encoded data as a byte array. public byte[] RLPData => GetRLPData(); + /// + /// Returns the encoded RLP data. + /// + /// A byte array of the RLP encoded data. Returns null if the data is empty. private byte[] GetRLPData() { return rlpData.Length == 0 ? null : rlpData; diff --git a/src/ChainSafe.Gaming/RPC/RLP/RLPStringFormatter.cs b/src/ChainSafe.Gaming/RPC/RLP/RLPStringFormatter.cs index f1fd2a680..8d22a84e6 100644 --- a/src/ChainSafe.Gaming/RPC/RLP/RLPStringFormatter.cs +++ b/src/ChainSafe.Gaming/RPC/RLP/RLPStringFormatter.cs @@ -4,8 +4,17 @@ namespace ChainSafe.Gaming.Evm.RLP { + /// + /// Provides methods to format and convert RLPElements to string. + /// public class RLPStringFormatter { + /// + /// Converts an IRLPElement object to string in hexadecimal format. + /// + /// The IRLPElement object being converted. + /// The string format of the IRLPElement object in hexadecimal form. + /// Thrown when the RLPElement object is null. public static string Format(IRLPElement element) { var output = new StringBuilder(); diff --git a/src/ChainSafe.Gaming/RPC/SigningKey/SigningKey.cs b/src/ChainSafe.Gaming/RPC/SigningKey/SigningKey.cs index 5db94a2f1..8ae66933c 100644 --- a/src/ChainSafe.Gaming/RPC/SigningKey/SigningKey.cs +++ b/src/ChainSafe.Gaming/RPC/SigningKey/SigningKey.cs @@ -3,6 +3,9 @@ namespace ChainSafe.Gaming.Evm.SigningKey { + /// + /// Creates a new instance of the SigningKey class. + /// public class SigningKey { // private readonly string _curve; @@ -10,6 +13,10 @@ public class SigningKey // private readonly string _publicKey; private readonly ECKey ecKey; + /// + /// Initializes a new instance of the class with a private key. + /// + /// The private key as a hex string. public SigningKey(string privateKey) { // this.privateKey = privateKey; @@ -21,13 +28,25 @@ public SigningKey(string privateKey) ecKey = new ECKey(privateKey.HexToByteArray(), true); } + /// + /// Initializes a new instance of the class with a private key. + /// + /// The private key as a byte array. public SigningKey(byte[] privateKey) : this(Bytes.Bytes.Hexlify(privateKey)) { } + /// + /// Get the private key. + /// + /// The private key as a hex string. public string PrivateKey => "0x" + ecKey.PrivateKey.D.ToByteArray().ToHex(); + /// + /// Get the compressed public key. + /// + /// The compressed public key as a hex string. public string CompressedPublicKey => ecKey.GetPubKey(true).ToHex(true); } } \ No newline at end of file diff --git a/src/ChainSafe.Gaming/RPC/Transactions/Formatter.cs b/src/ChainSafe.Gaming/RPC/Transactions/Formatter.cs index 90c2e1482..44d3014ce 100644 --- a/src/ChainSafe.Gaming/RPC/Transactions/Formatter.cs +++ b/src/ChainSafe.Gaming/RPC/Transactions/Formatter.cs @@ -6,8 +6,16 @@ namespace ChainSafe.Gaming.Evm.Transactions { + /// + /// Class to format and parse transactions. + /// public class Formatter { + /// + /// Parses a signed transaction. + /// + /// The signed transaction as a string to be parsed. + /// A Transaction object representing the parsed transaction. public Transaction Parse(string signedTx) { var payload = signedTx.HexToByteArray(); @@ -28,6 +36,11 @@ public Transaction Parse(string signedTx) throw new Exception($"unsupported transaction type: {payload[0]}"); } + /// + /// Parses a payload of a transaction. + /// + /// The byte array of the payload to be parsed. + /// A Transaction object representing the parsed transaction. private Transaction Parse(byte[] payload) { var decodedList = RLP.RLP.Decode(payload); @@ -103,6 +116,11 @@ private Transaction Parse(byte[] payload) return tx; } + /// + /// Parses a payload of a transaction according to the EIP-2930 standard. + /// + /// The byte array of the payload to be parsed. + /// A Transaction object representing the parsed EIP-2930 transaction. private Transaction ParseEip2930(byte[] payload) { var decodedList = RLP.RLP.Decode(payload.Skip(1).ToArray()); diff --git a/src/ChainSafe.Gaming/RPC/Utils/IsUnityBuild.cs b/src/ChainSafe.Gaming/RPC/Utils/IsUnityBuild.cs index 04d4004b6..f512d9a37 100644 --- a/src/ChainSafe.Gaming/RPC/Utils/IsUnityBuild.cs +++ b/src/ChainSafe.Gaming/RPC/Utils/IsUnityBuild.cs @@ -1,6 +1,9 @@ #if Unity namespace ChainSafe.Gaming.Evm.Utils { + /// + /// Defines the class. + /// public class IsUnityBuild { } diff --git a/src/ChainSafe.Gaming/RPC/Utils/Units.cs b/src/ChainSafe.Gaming/RPC/Utils/Units.cs index 0bf766b2a..feabf6585 100644 --- a/src/ChainSafe.Gaming/RPC/Utils/Units.cs +++ b/src/ChainSafe.Gaming/RPC/Utils/Units.cs @@ -4,6 +4,9 @@ namespace ChainSafe.Gaming.Evm.Utils { + /// + /// A utility class for unit conversion regarding Ethereum's native currency. + /// public class Units { private static readonly string[] Names = new string[] @@ -17,27 +20,55 @@ public class Units "ether", }; + /// + /// Converts Wei to Ether. + /// + /// The Wei amount to be converted to Ether. + /// A string representing the converted Ether amount. public static string FormatEther(BigInteger wei) { return FormatUnits(wei, 18); } + /// + /// Converts Ether to Wei. + /// + /// The Ether amount to be converted to Wei. + /// A BigInteger representing the converted Wei amount. public static BigInteger ParseEther(string ether) { return ParseUnits(ether, 18); } + /// + /// Formats units based on the given decimals. + /// + /// The value to format. + /// The number of decimals to be used for the formatting. + /// A string representing the formatted units. public static string FormatUnits(BigInteger value, int decimals) { return new BigDecimal(value, decimals * -1).ToString(); } + /// + /// Formats units based on the given unit name. + /// + /// The value to format. + /// The name of the unit to be used for the formatting. + /// A string representing the formatted units. public static string FormatUnits(BigInteger value, string unitName) { var unitIndex = Array.IndexOf(Names, unitName); return unitIndex == -1 ? FormatUnits(value, 18) : FormatUnits(value, unitIndex * 3); } + /// + /// Parses units based on the given decimals. + /// + /// The value to parse. + /// The number of decimals to be used for parsing. + /// A BigInteger representing the parsed units. public static BigInteger ParseUnits(BigDecimal value, int decimals) { var bigDecimalFromUnit = new BigDecimal(decimals, 0); @@ -45,11 +76,23 @@ public static BigInteger ParseUnits(BigDecimal value, int decimals) return conversion.Floor().Mantissa; } + /// + /// Parses units based on the given decimals. + /// + /// The value to parse. + /// The number of decimals to be used for parsing. + /// A BigInteger representing the parsed units. public static BigInteger ParseUnits(string value, int decimals) { return ParseUnits(decimal.Parse(value), decimals); } + /// + /// Parses units based on the given unit name. + /// + /// The value to parse. + /// The name of the unit to be used for parsing. + /// A BigInteger representing the parsed units. public static BigInteger ParseUnits(string value, string unitName) { var unitIndex = Array.IndexOf(Names, unitName); diff --git a/src/UnitySampleProject/Assets/Samples/web3.unity SDK/2.5.0/Web3.Unity Samples/Scripts/Scenes/Login.cs b/src/UnitySampleProject/Assets/Samples/web3.unity SDK/2.5.0/Web3.Unity Samples/Scripts/Scenes/Login.cs index b1d0fa7fd..d5a8a00d1 100644 --- a/src/UnitySampleProject/Assets/Samples/web3.unity SDK/2.5.0/Web3.Unity Samples/Scripts/Scenes/Login.cs +++ b/src/UnitySampleProject/Assets/Samples/web3.unity SDK/2.5.0/Web3.Unity Samples/Scripts/Scenes/Login.cs @@ -55,41 +55,42 @@ public class Login : MonoBehaviour public Toggle RememberMeToggle; public ErrorPopup ErrorPopup; public List Web3AuthButtons; - + private bool useWalletConnect; private bool redirectToWallet; - + private Dictionary supportedWallets; - + #region Wallet Connect private WalletConnectConfig walletConnectConfig; private bool autoLogin; - + [field: Header("Wallet Connect")] [SerializeField] private TMP_Dropdown supportedWalletsDropdown; - + [SerializeField] private Toggle redirectToWalletToggle; - + [SerializeField] private WalletConnectModal walletConnectModal; - + [field: SerializeField] public string ProjectId { get; private set; } - + [field: SerializeField] public string ProjectName { get; private set; } - + [field: SerializeField] public string BaseContext { get; private set; } - - [field: SerializeField] public Metadata Metadata { get; private set; } = new Metadata + + [field: SerializeField] + public Metadata Metadata { get; private set; } = new Metadata { Name = "Web3.Unity", //from package.json Description = "web3.unity is an open-source gaming SDK written in C# and developed by ChainSafe Gaming. It connects games built in the Unity game engine to the blockchain. The library currently supports games built for web browsers (WebGL), iOS/Android mobile, and desktop. web3.unity is compatible with most EVM-based chains such as Ethereum, Polygon, Moonbeam, Cronos, Nervos, and Binance Smart Chain, letting developers easily choose and switch between them to create the best in-game experience.", Url = "https://chainsafe.io/" }; - + #endregion private IEnumerator Start() @@ -104,7 +105,7 @@ private IEnumerator Start() // Remember me only works with the WebPageWallet RememberMeToggle.gameObject.SetActive(useWalletConnect); - + // Wallet Connect yield return FetchSupportedWallets(); @@ -118,7 +119,7 @@ private IEnumerator Start() ProcessWeb3Auth(); #endif var autoLoginTask = TryAutoLogin(); - + yield return new WaitUntil(() => autoLoginTask.IsCompleted); ExistingWalletButton.onClick.AddListener(OnLoginWithExistingAccount); @@ -156,14 +157,14 @@ private void WalletConnected(ConnectedData data) walletConnectModal.WalletConnected(data); } } - + private void SessionApproved(SessionStruct session) { // save/persist session if (walletConnectConfig.KeepSessionAlive) { walletConnectConfig.SavedSessionTopic = session.Topic; - + PlayerPrefs.SetString(SavedWalletConnectConfigKey, JsonConvert.SerializeObject(walletConnectConfig)); } @@ -172,7 +173,7 @@ private void SessionApproved(SessionStruct session) // reset if any saved config PlayerPrefs.SetString(SavedWalletConnectConfigKey, null); } - + Debug.Log($"{session.Topic} Approved"); } @@ -184,7 +185,7 @@ private void InitializeMobileOptions() InitializeWalletDropdown(); #endif } - + // add all supported wallets private void InitializeWalletDropdown() { @@ -192,19 +193,19 @@ private void InitializeWalletDropdown() { supportedWalletsDropdown.gameObject.SetActive(isOn); }); - + // first element is a no select List supportedWalletsList = new List { // default option/unselected - "Select Wallet", + "Select Wallet", }; supportedWalletsList.AddRange(supportedWallets.Values.Select(w => w.Name)); - + supportedWalletsDropdown.AddOptions(supportedWalletsList); } - + private async Task TryAutoLogin() { if (!useWalletConnect) @@ -218,13 +219,13 @@ private async Task TryAutoLogin() } Debug.Log("Attempting to Auto Login..."); - + try { autoLogin = true; - + walletConnectConfig = JsonConvert.DeserializeObject(savedConfigJson); - + await LoginWithExistingAccount(); } catch (Exception e) @@ -250,7 +251,7 @@ private async void OnLoginWithExistingAccount() await LoginWithExistingAccount(); } - + private async Task LoginWithExistingAccount() { var web3Builder = new Web3Builder(ProjectConfigUtilities.Load()) @@ -429,14 +430,14 @@ private WalletConnectConfig BuildWalletConnectConfig() }; walletConnectConfig = config; - + walletConnectConfig.OnConnected += WalletConnected; walletConnectConfig.OnSessionApproved += SessionApproved; - + return config; } - + private IEnumerator FetchSupportedWallets() { using (UnityWebRequest webRequest = UnityWebRequest.Get("https://registry.walletconnect.org/data/wallets.json")) @@ -447,16 +448,16 @@ private IEnumerator FetchSupportedWallets() if (webRequest.result != UnityWebRequest.Result.Success) { Debug.LogError("Error Getting Supported Wallets: " + webRequest.error); - + yield return null; } - + else { var json = webRequest.downloadHandler.text; supportedWallets = JsonConvert.DeserializeObject>(json) - .ToDictionary(w => w.Key, w => (WalletConnectWalletModel) w.Value); + .ToDictionary(w => w.Key, w => (WalletConnectWalletModel)w.Value); Debug.Log($"Fetched {supportedWallets.Count} Supported Wallets."); } diff --git a/src/UnitySampleProject/Assets/Samples/web3.unity SDK/2.5.0/Web3.Unity Samples/Scripts/Utilities/WalletConnectModal.cs b/src/UnitySampleProject/Assets/Samples/web3.unity SDK/2.5.0/Web3.Unity Samples/Scripts/Utilities/WalletConnectModal.cs index 9cff96696..a983e8ea4 100644 --- a/src/UnitySampleProject/Assets/Samples/web3.unity SDK/2.5.0/Web3.Unity Samples/Scripts/Utilities/WalletConnectModal.cs +++ b/src/UnitySampleProject/Assets/Samples/web3.unity SDK/2.5.0/Web3.Unity Samples/Scripts/Utilities/WalletConnectModal.cs @@ -15,7 +15,7 @@ public class WalletConnectModal : MonoBehaviour [SerializeField] private Button _backButton; [SerializeField] private Transform _container; - + private void Start() { _backButton.onClick.AddListener(Disable); @@ -44,7 +44,8 @@ private static Color32[] Encode(string textForEncoding, int width, int height) { var writer = new BarcodeWriter { - Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width } + Format = BarcodeFormat.QR_CODE, + Options = new QrCodeEncodingOptions { Height = height, Width = width } }; return writer.Write(textForEncoding); } @@ -55,7 +56,7 @@ private void GenerateQrCode(string text) var color32 = Encode(text, encoded.width, encoded.height); encoded.SetPixels32(color32); encoded.Apply(); - + // Convert the texture into a sprite and assign it to our QR code image var qrCodeSprite = Sprite.Create(encoded, new Rect(0, 0, encoded.width, encoded.height), new Vector2(0.5f, 0.5f), 100f); From 7a84c3f93b14b9a4766fd028b8f028217da669e8 Mon Sep 17 00:00:00 2001 From: kalambet Date: Thu, 19 Oct 2023 23:14:05 +0000 Subject: [PATCH 2/3] Auto-duplicate Package Samples --- .../Web3.Unity/Scripts/Scenes/Login.cs | 65 ++++++++++--------- .../Scripts/Utilities/WalletConnectModal.cs | 7 +- 2 files changed, 37 insertions(+), 35 deletions(-) diff --git a/Packages/io.chainsafe.web3-unity/Samples~/Web3.Unity/Scripts/Scenes/Login.cs b/Packages/io.chainsafe.web3-unity/Samples~/Web3.Unity/Scripts/Scenes/Login.cs index b1d0fa7fd..d5a8a00d1 100644 --- a/Packages/io.chainsafe.web3-unity/Samples~/Web3.Unity/Scripts/Scenes/Login.cs +++ b/Packages/io.chainsafe.web3-unity/Samples~/Web3.Unity/Scripts/Scenes/Login.cs @@ -55,41 +55,42 @@ public class Login : MonoBehaviour public Toggle RememberMeToggle; public ErrorPopup ErrorPopup; public List Web3AuthButtons; - + private bool useWalletConnect; private bool redirectToWallet; - + private Dictionary supportedWallets; - + #region Wallet Connect private WalletConnectConfig walletConnectConfig; private bool autoLogin; - + [field: Header("Wallet Connect")] [SerializeField] private TMP_Dropdown supportedWalletsDropdown; - + [SerializeField] private Toggle redirectToWalletToggle; - + [SerializeField] private WalletConnectModal walletConnectModal; - + [field: SerializeField] public string ProjectId { get; private set; } - + [field: SerializeField] public string ProjectName { get; private set; } - + [field: SerializeField] public string BaseContext { get; private set; } - - [field: SerializeField] public Metadata Metadata { get; private set; } = new Metadata + + [field: SerializeField] + public Metadata Metadata { get; private set; } = new Metadata { Name = "Web3.Unity", //from package.json Description = "web3.unity is an open-source gaming SDK written in C# and developed by ChainSafe Gaming. It connects games built in the Unity game engine to the blockchain. The library currently supports games built for web browsers (WebGL), iOS/Android mobile, and desktop. web3.unity is compatible with most EVM-based chains such as Ethereum, Polygon, Moonbeam, Cronos, Nervos, and Binance Smart Chain, letting developers easily choose and switch between them to create the best in-game experience.", Url = "https://chainsafe.io/" }; - + #endregion private IEnumerator Start() @@ -104,7 +105,7 @@ private IEnumerator Start() // Remember me only works with the WebPageWallet RememberMeToggle.gameObject.SetActive(useWalletConnect); - + // Wallet Connect yield return FetchSupportedWallets(); @@ -118,7 +119,7 @@ private IEnumerator Start() ProcessWeb3Auth(); #endif var autoLoginTask = TryAutoLogin(); - + yield return new WaitUntil(() => autoLoginTask.IsCompleted); ExistingWalletButton.onClick.AddListener(OnLoginWithExistingAccount); @@ -156,14 +157,14 @@ private void WalletConnected(ConnectedData data) walletConnectModal.WalletConnected(data); } } - + private void SessionApproved(SessionStruct session) { // save/persist session if (walletConnectConfig.KeepSessionAlive) { walletConnectConfig.SavedSessionTopic = session.Topic; - + PlayerPrefs.SetString(SavedWalletConnectConfigKey, JsonConvert.SerializeObject(walletConnectConfig)); } @@ -172,7 +173,7 @@ private void SessionApproved(SessionStruct session) // reset if any saved config PlayerPrefs.SetString(SavedWalletConnectConfigKey, null); } - + Debug.Log($"{session.Topic} Approved"); } @@ -184,7 +185,7 @@ private void InitializeMobileOptions() InitializeWalletDropdown(); #endif } - + // add all supported wallets private void InitializeWalletDropdown() { @@ -192,19 +193,19 @@ private void InitializeWalletDropdown() { supportedWalletsDropdown.gameObject.SetActive(isOn); }); - + // first element is a no select List supportedWalletsList = new List { // default option/unselected - "Select Wallet", + "Select Wallet", }; supportedWalletsList.AddRange(supportedWallets.Values.Select(w => w.Name)); - + supportedWalletsDropdown.AddOptions(supportedWalletsList); } - + private async Task TryAutoLogin() { if (!useWalletConnect) @@ -218,13 +219,13 @@ private async Task TryAutoLogin() } Debug.Log("Attempting to Auto Login..."); - + try { autoLogin = true; - + walletConnectConfig = JsonConvert.DeserializeObject(savedConfigJson); - + await LoginWithExistingAccount(); } catch (Exception e) @@ -250,7 +251,7 @@ private async void OnLoginWithExistingAccount() await LoginWithExistingAccount(); } - + private async Task LoginWithExistingAccount() { var web3Builder = new Web3Builder(ProjectConfigUtilities.Load()) @@ -429,14 +430,14 @@ private WalletConnectConfig BuildWalletConnectConfig() }; walletConnectConfig = config; - + walletConnectConfig.OnConnected += WalletConnected; walletConnectConfig.OnSessionApproved += SessionApproved; - + return config; } - + private IEnumerator FetchSupportedWallets() { using (UnityWebRequest webRequest = UnityWebRequest.Get("https://registry.walletconnect.org/data/wallets.json")) @@ -447,16 +448,16 @@ private IEnumerator FetchSupportedWallets() if (webRequest.result != UnityWebRequest.Result.Success) { Debug.LogError("Error Getting Supported Wallets: " + webRequest.error); - + yield return null; } - + else { var json = webRequest.downloadHandler.text; supportedWallets = JsonConvert.DeserializeObject>(json) - .ToDictionary(w => w.Key, w => (WalletConnectWalletModel) w.Value); + .ToDictionary(w => w.Key, w => (WalletConnectWalletModel)w.Value); Debug.Log($"Fetched {supportedWallets.Count} Supported Wallets."); } diff --git a/Packages/io.chainsafe.web3-unity/Samples~/Web3.Unity/Scripts/Utilities/WalletConnectModal.cs b/Packages/io.chainsafe.web3-unity/Samples~/Web3.Unity/Scripts/Utilities/WalletConnectModal.cs index 9cff96696..a983e8ea4 100644 --- a/Packages/io.chainsafe.web3-unity/Samples~/Web3.Unity/Scripts/Utilities/WalletConnectModal.cs +++ b/Packages/io.chainsafe.web3-unity/Samples~/Web3.Unity/Scripts/Utilities/WalletConnectModal.cs @@ -15,7 +15,7 @@ public class WalletConnectModal : MonoBehaviour [SerializeField] private Button _backButton; [SerializeField] private Transform _container; - + private void Start() { _backButton.onClick.AddListener(Disable); @@ -44,7 +44,8 @@ private static Color32[] Encode(string textForEncoding, int width, int height) { var writer = new BarcodeWriter { - Format = BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width } + Format = BarcodeFormat.QR_CODE, + Options = new QrCodeEncodingOptions { Height = height, Width = width } }; return writer.Write(textForEncoding); } @@ -55,7 +56,7 @@ private void GenerateQrCode(string text) var color32 = Encode(text, encoded.width, encoded.height); encoded.SetPixels32(color32); encoded.Apply(); - + // Convert the texture into a sprite and assign it to our QR code image var qrCodeSprite = Sprite.Create(encoded, new Rect(0, 0, encoded.width, encoded.height), new Vector2(0.5f, 0.5f), 100f); From e76fb022d435facf1fe806329b058cefa32e5738 Mon Sep 17 00:00:00 2001 From: Peter Kalambet Date: Fri, 20 Oct 2023 01:23:37 +0200 Subject: [PATCH 3/3] retrigger checks