Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Refactor] Added Prefer var everywhere #3216

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,9 @@ csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = false

# Prefer "var" everywhere
csharp_style_var_for_built_in_types = true:suggestion
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_elsewhere = true:suggestion
csharp_style_var_for_built_in_types = true:warning
csharp_style_var_when_type_is_apparent = true:warning
csharp_style_var_elsewhere = true:warning

# Prefer method-like constructs to have a block body
csharp_style_expression_bodied_methods = false:none
Expand Down Expand Up @@ -285,9 +285,6 @@ dotnet_diagnostic.CA1822.severity = warning

# Prefer "var" everywhere
dotnet_diagnostic.IDE0007.severity = warning
csharp_style_var_for_built_in_types = true:warning
csharp_style_var_when_type_is_apparent = true:warning
csharp_style_var_elsewhere = true:warning

# csharp_style_allow_embedded_statements_on_same_line_experimental
dotnet_diagnostic.IDE2001.severity = warning
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/Neo.Benchmarks/Benchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ private static void Run(string name, string poc)
using var snapshot = system.GetSnapshot();
using var engine = ApplicationEngine.Create(TriggerType.Application, tx, snapshot, system.GenesisBlock, protocol, tx.SystemFee);
engine.LoadScript(tx.Script);
Stopwatch stopwatch = Stopwatch.StartNew();
var stopwatch = Stopwatch.StartNew();
engine.Execute();
stopwatch.Stop();
Debug.Assert(engine.State == VMState.FAULT);
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/Neo.VM.Benchmarks/Benchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,10 @@ public static void NeoIssue2723()

private static void Run(string name, string poc)
{
byte[] script = Convert.FromBase64String(poc);
var script = Convert.FromBase64String(poc);
using ExecutionEngine engine = new();
engine.LoadScript(script);
Stopwatch stopwatch = Stopwatch.StartNew();
var stopwatch = Stopwatch.StartNew();
engine.Execute();
stopwatch.Stop();
Debug.Assert(engine.State == VMState.HALT);
Expand Down
6 changes: 3 additions & 3 deletions src/Neo.CLI/CLI/MainService.Blockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ partial class MainService
[ConsoleCommand("export blocks", Category = "Blockchain Commands")]
private void OnExportBlocksStartCountCommand(uint start, uint count = uint.MaxValue, string? path = null)
{
uint height = NativeContract.Ledger.CurrentIndex(NeoSystem.StoreView);
var height = NativeContract.Ledger.CurrentIndex(NeoSystem.StoreView);
if (height < start)
{
ConsoleHelper.Error("invalid start height.");
Expand Down Expand Up @@ -69,7 +69,7 @@ private void OnShowBlockCommand(string indexOrHash)
return;
}

DateTime blockDatetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var blockDatetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
blockDatetime = blockDatetime.AddMilliseconds(block.Timestamp).ToLocalTime();

ConsoleHelper.Info("", "-------------", "Block", "-------------");
Expand Down Expand Up @@ -127,7 +127,7 @@ public void OnShowTransactionCommand(UInt256 hash)

var block = NativeContract.Ledger.GetHeader(NeoSystem.StoreView, tx.BlockIndex);

DateTime transactionDatetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var transactionDatetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
transactionDatetime = transactionDatetime.AddMilliseconds(block.Timestamp).ToLocalTime();

ConsoleHelper.Info("", "-------------", "Transaction", "-------------");
Expand Down
14 changes: 7 additions & 7 deletions src/Neo.CLI/CLI/MainService.Contracts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ partial class MainService
private void OnDeployCommand(string filePath, string? manifestPath = null, JObject? data = null)
{
if (NoWallet()) return;
byte[] script = LoadDeploymentScript(filePath, manifestPath, data, out var nef, out var manifest);
var script = LoadDeploymentScript(filePath, manifestPath, data, out var nef, out var manifest);
Transaction tx;
try
{
Expand All @@ -43,7 +43,7 @@ private void OnDeployCommand(string filePath, string? manifestPath = null, JObje
ConsoleHelper.Error(GetExceptionMessage(e));
return;
}
UInt160 hash = SmartContract.Helper.GetContractHash(tx.Sender, nef.CheckSum, manifest.Name);
var hash = SmartContract.Helper.GetContractHash(tx.Sender, nef.CheckSum, manifest.Name);

ConsoleHelper.Info("Contract hash: ", $"{hash}");
ConsoleHelper.Info("Gas consumed: ", $"{new BigDecimal((BigInteger)tx.SystemFee, NativeContract.GAS.Decimals)}");
Expand All @@ -68,7 +68,7 @@ private void OnDeployCommand(string filePath, string? manifestPath = null, JObje
[ConsoleCommand("update", Category = "Contract Commands")]
private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifestPath, UInt160 sender, UInt160[]? signerAccounts = null, JObject? data = null)
{
Signer[] signers = Array.Empty<Signer>();
var signers = Array.Empty<Signer>();

if (NoWallet()) return;
if (sender != null)
Expand All @@ -91,15 +91,15 @@ private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifes
Transaction tx;
try
{
byte[] script = LoadUpdateScript(scriptHash, filePath, manifestPath, data, out var nef, out var manifest);
var script = LoadUpdateScript(scriptHash, filePath, manifestPath, data, out var nef, out var manifest);
tx = CurrentWallet!.MakeTransaction(NeoSystem.StoreView, script, sender, signers);
}
catch (InvalidOperationException e)
{
ConsoleHelper.Error(GetExceptionMessage(e));
return;
}
ContractState contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, scriptHash);
var contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, scriptHash);
if (contract == null)
{
ConsoleHelper.Warning($"Can't upgrade, contract hash not exist: {scriptHash}");
Expand Down Expand Up @@ -132,7 +132,7 @@ private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifes
private void OnInvokeCommand(UInt160 scriptHash, string operation, JArray? contractParameters = null, UInt160? sender = null, UInt160[]? signerAccounts = null, decimal maxGas = 20)
{
var gas = new BigDecimal(maxGas, NativeContract.GAS.Decimals);
Signer[] signers = Array.Empty<Signer>();
var signers = Array.Empty<Signer>();
if (!NoWallet())
{
if (sender == null)
Expand All @@ -156,7 +156,7 @@ private void OnInvokeCommand(UInt160 scriptHash, string operation, JArray? contr
}
}

Transaction tx = new Transaction
var tx = new Transaction
{
Signers = signers,
Attributes = Array.Empty<TransactionAttribute>(),
Expand Down
4 changes: 2 additions & 2 deletions src/Neo.CLI/CLI/MainService.Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ private static void GetErrorLogs(StringBuilder sb, Exception ex)
sb.AppendLine(ex.StackTrace);
if (ex is AggregateException ex2)
{
foreach (Exception inner in ex2.InnerExceptions)
foreach (var inner in ex2.InnerExceptions)
{
sb.AppendLine();
GetErrorLogs(sb, inner);
Expand All @@ -92,7 +92,7 @@ private void OnLog(string source, LogLevel level, object message)

lock (syncRoot)
{
DateTime now = DateTime.Now;
var now = DateTime.Now;
var log = $"[{now.TimeOfDay:hh\\:mm\\:ss\\.fff}]";
if (_showLog)
{
Expand Down
8 changes: 4 additions & 4 deletions src/Neo.CLI/CLI/MainService.NEP17.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private void OnBalanceOfCommand(UInt160 tokenHash, UInt160 address)

var asset = new AssetDescriptor(NeoSystem.StoreView, NeoSystem.Settings, tokenHash);

if (!OnInvokeWithResult(tokenHash, "balanceOf", out StackItem balanceResult, null, new JArray(arg))) return;
if (!OnInvokeWithResult(tokenHash, "balanceOf", out var balanceResult, null, new JArray(arg))) return;

var balance = new BigDecimal(((PrimitiveType)balanceResult).GetInteger(), asset.Decimals);

Expand All @@ -105,7 +105,7 @@ private void OnBalanceOfCommand(UInt160 tokenHash, UInt160 address)
[ConsoleCommand("name", Category = "NEP17 Commands")]
private void OnNameCommand(UInt160 tokenHash)
{
ContractState contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, tokenHash);
var contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, tokenHash);
if (contract == null) Console.WriteLine($"Contract hash not exist: {tokenHash}");
else ConsoleHelper.Info("Result: ", contract.Manifest.Name);
}
Expand All @@ -117,7 +117,7 @@ private void OnNameCommand(UInt160 tokenHash)
[ConsoleCommand("decimals", Category = "NEP17 Commands")]
private void OnDecimalsCommand(UInt160 tokenHash)
{
if (!OnInvokeWithResult(tokenHash, "decimals", out StackItem result)) return;
if (!OnInvokeWithResult(tokenHash, "decimals", out var result)) return;

ConsoleHelper.Info("Result: ", $"{((PrimitiveType)result).GetInteger()}");
}
Expand All @@ -129,7 +129,7 @@ private void OnDecimalsCommand(UInt160 tokenHash)
[ConsoleCommand("totalSupply", Category = "NEP17 Commands")]
private void OnTotalSupplyCommand(UInt160 tokenHash)
{
if (!OnInvokeWithResult(tokenHash, "totalSupply", out StackItem result)) return;
if (!OnInvokeWithResult(tokenHash, "totalSupply", out var result)) return;

var asset = new AssetDescriptor(NeoSystem.StoreView, NeoSystem.Settings, tokenHash);
var totalSupply = new BigDecimal(((PrimitiveType)result).GetInteger(), asset.Decimals);
Expand Down
4 changes: 2 additions & 2 deletions src/Neo.CLI/CLI/MainService.Network.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ private void OnBroadcastInvCommand(InventoryType type, UInt256[] payload)
[ConsoleCommand("broadcast transaction", Category = "Network Commands")]
private void OnBroadcastTransactionCommand(UInt256 hash)
{
if (NeoSystem.MemPool.TryGetValue(hash, out Transaction tx))
if (NeoSystem.MemPool.TryGetValue(hash, out var tx))
OnBroadcastCommand(MessageCommand.Transaction, tx);
}

Expand All @@ -141,7 +141,7 @@ private void OnRelayCommand(JObject jsonObjectToRelay)

try
{
ContractParametersContext context = ContractParametersContext.Parse(jsonObjectToRelay.ToString(), NeoSystem.StoreView);
var context = ContractParametersContext.Parse(jsonObjectToRelay.ToString(), NeoSystem.StoreView);
if (!context.Completed)
{
ConsoleHelper.Error("The signature is incomplete.");
Expand Down
22 changes: 11 additions & 11 deletions src/Neo.CLI/CLI/MainService.Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ private void OnShowPoolCommand(bool verbose = false)
if (verbose)
{
NeoSystem.MemPool.GetVerifiedAndUnverifiedTransactions(
out IEnumerable<Transaction> verifiedTransactions,
out IEnumerable<Transaction> unverifiedTransactions);
out var verifiedTransactions,
out var unverifiedTransactions);
ConsoleHelper.Info("Verified Transactions:");
foreach (Transaction tx in verifiedTransactions)
foreach (var tx in verifiedTransactions)
Console.WriteLine($" {tx.Hash} {tx.GetType().Name} {tx.NetworkFee} GAS_NetFee");
ConsoleHelper.Info("Unverified Transactions:");
foreach (Transaction tx in unverifiedTransactions)
foreach (var tx in unverifiedTransactions)
Console.WriteLine($" {tx.Hash} {tx.GetType().Name} {tx.NetworkFee} GAS_NetFee");

verifiedCount = verifiedTransactions.Count();
Expand All @@ -65,27 +65,27 @@ private void OnShowStateCommand()
Console.CursorVisible = false;
Console.Clear();

Task broadcast = Task.Run(async () =>
var broadcast = Task.Run(async () =>
{
while (!cancel.Token.IsCancellationRequested)
{
NeoSystem.LocalNode.Tell(Message.Create(MessageCommand.Ping, PingPayload.Create(NativeContract.Ledger.CurrentIndex(NeoSystem.StoreView))));
await Task.Delay(NeoSystem.Settings.TimePerBlock, cancel.Token);
}
});
Task task = Task.Run(async () =>
var task = Task.Run(async () =>
{
int maxLines = 0;
var maxLines = 0;
while (!cancel.Token.IsCancellationRequested)
{
uint height = NativeContract.Ledger.CurrentIndex(NeoSystem.StoreView);
uint headerHeight = NeoSystem.HeaderCache.Last?.Index ?? height;
var height = NativeContract.Ledger.CurrentIndex(NeoSystem.StoreView);
var headerHeight = NeoSystem.HeaderCache.Last?.Index ?? height;

Console.SetCursorPosition(0, 0);
WriteLineWithoutFlicker($"block: {height}/{headerHeight} connected: {LocalNode.ConnectedCount} unconnected: {LocalNode.UnconnectedCount}", Console.WindowWidth - 1);

int linesWritten = 1;
foreach (RemoteNode node in LocalNode.GetRemoteNodes().OrderByDescending(u => u.LastBlockIndex).Take(Console.WindowHeight - 2).ToArray())
var linesWritten = 1;
foreach (var node in LocalNode.GetRemoteNodes().OrderByDescending(u => u.LastBlockIndex).Take(Console.WindowHeight - 2).ToArray())
{
ConsoleHelper.Info(" ip: ",
$"{node.Remote.Address,-15}\t",
Expand Down
2 changes: 1 addition & 1 deletion src/Neo.CLI/CLI/MainService.Plugins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ private void OnPluginsCommand()
if (installedPlugin != null)
{
var maxLength = plugins.Select(s => s.Length).OrderDescending().First();
string tabs = string.Empty;
var tabs = string.Empty;
if (f.Length < maxLength)
tabs = "\t";
ConsoleHelper.Info("", $"[Installed]\t {f,6}{tabs}", " @", $"{installedPlugin.Version.ToString(3)} {installedPlugin.Description}");
Expand Down
28 changes: 14 additions & 14 deletions src/Neo.CLI/CLI/MainService.Tools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private void OnParseCommand(string value)
{ "String to Base64", StringToBase64 }
};

bool any = false;
var any = false;

foreach (var pair in parseFunctions)
{
Expand Down Expand Up @@ -129,7 +129,7 @@ private void OnParseCommand(string value)
/// </exception>
private string ClearHexString(string hexString)
{
bool hasHexPrefix = hexString.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase);
var hasHexPrefix = hexString.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase);

try
{
Expand Down Expand Up @@ -200,8 +200,8 @@ private string ClearHexString(string hexString)
{
try
{
byte[] bytearray = Utility.StrictUTF8.GetBytes(strParam);
string base64 = Convert.ToBase64String(bytearray.AsSpan());
var bytearray = Utility.StrictUTF8.GetBytes(strParam);
var base64 = Convert.ToBase64String(bytearray.AsSpan());
return base64;
}
catch
Expand Down Expand Up @@ -256,8 +256,8 @@ private string ClearHexString(string hexString)
{
return null;
}
byte[] bytearray = number.ToByteArray();
string base64 = Convert.ToBase64String(bytearray.AsSpan());
var bytearray = number.ToByteArray();
var base64 = Convert.ToBase64String(bytearray.AsSpan());

return base64;
}
Expand Down Expand Up @@ -308,7 +308,7 @@ private string ClearHexString(string hexString)
try
{
var script = address.ToScriptHash(NeoSystem.Settings.AddressVersion);
string base64 = Convert.ToBase64String(script.ToArray().AsSpan());
var base64 = Convert.ToBase64String(script.ToArray().AsSpan());

return base64;
}
Expand Down Expand Up @@ -342,11 +342,11 @@ private string ClearHexString(string hexString)
}
else
{
if (!UInt160.TryParse(script, out UInt160 littleEndScript))
if (!UInt160.TryParse(script, out var littleEndScript))
{
return null;
}
string bigEndScript = littleEndScript.ToArray().ToHexString();
var bigEndScript = littleEndScript.ToArray().ToHexString();
if (!UInt160.TryParse(bigEndScript, out scriptHash))
{
return null;
Expand Down Expand Up @@ -377,15 +377,15 @@ private string ClearHexString(string hexString)
{
try
{
byte[] result = Convert.FromBase64String(bytearray).Reverse().ToArray();
string hex = result.ToHexString();
var result = Convert.FromBase64String(bytearray).Reverse().ToArray();
var hex = result.ToHexString();

if (!UInt160.TryParse(hex, out var scripthash))
{
return null;
}

string address = scripthash.ToAddress(NeoSystem.Settings.AddressVersion);
var address = scripthash.ToAddress(NeoSystem.Settings.AddressVersion);
return address;
}
catch
Expand All @@ -410,8 +410,8 @@ private string ClearHexString(string hexString)
{
try
{
byte[] result = Convert.FromBase64String(bytearray);
string utf8String = Utility.StrictUTF8.GetString(result);
var result = Convert.FromBase64String(bytearray);
var utf8String = Utility.StrictUTF8.GetString(result);
return IsPrintable(utf8String) ? utf8String : null;
}
catch
Expand Down
Loading