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

Set project as nullable #3042

Merged
merged 11 commits into from
Dec 31, 2023
Merged
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
6 changes: 3 additions & 3 deletions src/Neo.CLI/CLI/ConsolePercent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@ public class ConsolePercent : IDisposable
private readonly long _maxValue;
private long _value;
private decimal _lastFactor;
private string _lastPercent;
private string? _lastPercent;

private readonly int _x, _y;

private bool _inputRedirected;
private readonly bool _inputRedirected;

#endregion

Expand Down Expand Up @@ -99,7 +99,7 @@ public ConsolePercent(long value = 0, long maxValue = 100)
/// </summary>
public void Invalidate()
{
var factor = Math.Round((Percent / 100M), 1);
var factor = Math.Round(Percent / 100M, 1);
var percent = Percent.ToString("0.0").PadLeft(5, ' ');

if (_lastFactor == factor && _lastPercent == percent)
Expand Down
22 changes: 11 additions & 11 deletions src/Neo.CLI/CLI/MainService.Blockchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ partial class MainService
/// <param name="count">Number of blocks</param>
/// <param name="path">Path</param>
[ConsoleCommand("export blocks", Category = "Blockchain Commands")]
private void OnExportBlocksStartCountCommand(uint start, uint count = uint.MaxValue, string path = null)
private void OnExportBlocksStartCountCommand(uint start, uint count = uint.MaxValue, string? path = null)
{
uint height = NativeContract.Ledger.CurrentIndex(NeoSystem.StoreView);
if (height < start)
Expand All @@ -50,12 +50,12 @@ private void OnShowBlockCommand(string indexOrHash)
{
lock (syncRoot)
{
Block block = null;
Block? block = null;

if (uint.TryParse(indexOrHash, out var index))
block = NativeContract.Ledger.GetBlock(_neoSystem.StoreView, index);
block = NativeContract.Ledger.GetBlock(NeoSystem.StoreView, index);
else if (UInt256.TryParse(indexOrHash, out var hash))
block = NativeContract.Ledger.GetBlock(_neoSystem.StoreView, hash);
block = NativeContract.Ledger.GetBlock(NeoSystem.StoreView, hash);
else
{
ConsoleHelper.Error("Enter a valid block index or hash.");
Expand All @@ -81,7 +81,7 @@ private void OnShowBlockCommand(string indexOrHash)
ConsoleHelper.Info("", " PrevHash: ", $"{block.PrevHash}");
ConsoleHelper.Info("", " NextConsensus: ", $"{block.NextConsensus}");
ConsoleHelper.Info("", " PrimaryIndex: ", $"{block.PrimaryIndex}");
ConsoleHelper.Info("", " PrimaryPubKey: ", $"{NativeContract.NEO.GetCommittee(_neoSystem.GetSnapshot())[block.PrimaryIndex]}");
ConsoleHelper.Info("", " PrimaryPubKey: ", $"{NativeContract.NEO.GetCommittee(NeoSystem.GetSnapshot())[block.PrimaryIndex]}");
ConsoleHelper.Info("", " Version: ", $"{block.Version}");
ConsoleHelper.Info("", " Size: ", $"{block.Size} Byte(s)");
ConsoleHelper.Info();
Expand Down Expand Up @@ -116,15 +116,15 @@ public void OnShowTransactionCommand(UInt256 hash)
{
lock (syncRoot)
{
var tx = NativeContract.Ledger.GetTransactionState(_neoSystem.StoreView, hash);
var tx = NativeContract.Ledger.GetTransactionState(NeoSystem.StoreView, hash);

if (tx is null)
{
ConsoleHelper.Error($"Transaction {hash} doesn't exist.");
return;
}

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

DateTime transactionDatetime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
transactionDatetime = transactionDatetime.AddMilliseconds(block.Timestamp).ToLocalTime();
Expand Down Expand Up @@ -228,16 +228,16 @@ public void OnShowContractCommand(string nameOrHash)
{
lock (syncRoot)
{
ContractState contract = null;
ContractState? contract = null;

if (UInt160.TryParse(nameOrHash, out var scriptHash))
contract = NativeContract.ContractManagement.GetContract(_neoSystem.StoreView, scriptHash);
contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, scriptHash);
else
{
var nativeContract = NativeContract.Contracts.SingleOrDefault(s => s.Name.Equals(nameOrHash, StringComparison.InvariantCultureIgnoreCase));

if (nativeContract != null)
contract = NativeContract.ContractManagement.GetContract(_neoSystem.StoreView, nativeContract.Hash);
contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, nativeContract.Hash);
}

if (contract is null)
Expand All @@ -257,7 +257,7 @@ public void OnShowContractCommand(string nameOrHash)
ConsoleHelper.Info("", " Compiler: ", $"{contract.Nef.Compiler}");
ConsoleHelper.Info("", " SourceCode: ", $"{contract.Nef.Source}");
ConsoleHelper.Info("", " Trusts: ", $"[{string.Join(", ", contract.Manifest.Trusts.Select(s => s.ToJson()?.GetString()))}]");
if (contract.Manifest.Extra is null)
if (contract.Manifest.Extra is not null)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was a bug

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

someone must of changed the code, i don't write code like that.

{
foreach (var extra in contract.Manifest.Extra.Properties)
{
Expand Down
12 changes: 6 additions & 6 deletions src/Neo.CLI/CLI/MainService.Contracts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ partial class MainService
/// <param name="manifestPath">Manifest path</param>
/// <param name="data">Extra data for deploy</param>
[ConsoleCommand("deploy", Category = "Contract Commands")]
private void OnDeployCommand(string filePath, string manifestPath = null, JObject data = null)
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);
Transaction tx;
try
{
tx = CurrentWallet.MakeTransaction(NeoSystem.StoreView, script);
tx = CurrentWallet!.MakeTransaction(NeoSystem.StoreView, script);
}
catch (InvalidOperationException e)
{
Expand Down Expand Up @@ -65,7 +65,7 @@ private void OnDeployCommand(string filePath, string manifestPath = null, JObjec
/// <param name="signerAccounts">Signer Accounts</param>
/// <param name="data">Extra data for update</param>
[ConsoleCommand("update", Category = "Contract Commands")]
private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifestPath, UInt160 sender, UInt160[] signerAccounts = null, JObject data = null)
private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifestPath, UInt160 sender, UInt160[]? signerAccounts = null, JObject? data = null)
{
Signer[] signers = Array.Empty<Signer>();

Expand All @@ -91,7 +91,7 @@ private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifes
try
{
byte[] script = LoadUpdateScript(scriptHash, filePath, manifestPath, data, out var nef, out var manifest);
tx = CurrentWallet.MakeTransaction(NeoSystem.StoreView, script, sender, signers);
tx = CurrentWallet!.MakeTransaction(NeoSystem.StoreView, script, sender, signers);
}
catch (InvalidOperationException e)
{
Expand Down Expand Up @@ -128,7 +128,7 @@ private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifes
/// <param name="signerAccounts">Signer's accounts</param>
/// <param name="maxGas">Max fee for running the script</param>
[ConsoleCommand("invoke", Category = "Contract Commands")]
private void OnInvokeCommand(UInt160 scriptHash, string operation, JArray contractParameters = null, UInt160 sender = null, UInt160[] signerAccounts = null, decimal maxGas = 20)
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>();
Expand Down Expand Up @@ -161,7 +161,7 @@ private void OnInvokeCommand(UInt160 scriptHash, string operation, JArray contra
if (NoWallet()) return;
try
{
tx = CurrentWallet.MakeTransaction(NeoSystem.StoreView, tx.Script, sender, signers, maxGas: (long)gas.Value);
tx = CurrentWallet!.MakeTransaction(NeoSystem.StoreView, tx.Script, sender, signers, maxGas: (long)gas.Value);
}
catch (InvalidOperationException e)
{
Expand Down
10 changes: 7 additions & 3 deletions src/Neo.CLI/CLI/MainService.Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ private void OnLog(string source, LogLevel level, object message)
Console.Write($"{logLevel} {log} \t{messages[0],-20}");
for (var i = 1; i < messages.Length; i++)
{
if (messages[i].Length > 20)
if (messages[i]?.Length > 20)
{
messages[i] = $"{messages[i][..10]}...{messages[i][(messages[i].Length - 10)..]}";
messages[i] = $"{messages[i]![..10]}...{messages[i]![(messages[i]!.Length - 10)..]}";
}
Console.Write(i % 2 == 0 ? $"={messages[i]} " : $" {messages[i]}");
}
Expand Down Expand Up @@ -162,7 +162,11 @@ private static string[] Parse(string message)
{
messages.Add(string.Join(" ", d));
}
messages.Add(parts.LastOrDefault());
var last = parts.LastOrDefault();
if (last is not null)
{
messages.Add(last);
}
}

return messages.ToArray();
Expand Down
5 changes: 2 additions & 3 deletions src/Neo.CLI/CLI/MainService.NEP17.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
using Neo.VM.Types;
using Neo.Wallets;
using System;
using System.Collections.Generic;
using System.Linq;
using Array = System.Array;

Expand All @@ -34,7 +33,7 @@ partial class MainService
/// <param name="data">Data</param>
/// <param name="signersAccounts">Signer's accounts</param>
[ConsoleCommand("transfer", Category = "NEP17 Commands")]
private void OnTransferCommand(UInt160 tokenHash, UInt160 to, decimal amount, UInt160 from = null, string data = null, UInt160[] signersAccounts = null)
private void OnTransferCommand(UInt160 tokenHash, UInt160 to, decimal amount, UInt160? from = null, string? data = null, UInt160[]? signersAccounts = null)
{
var snapshot = NeoSystem.StoreView;
var asset = new AssetDescriptor(snapshot, NeoSystem.Settings, tokenHash);
Expand All @@ -45,7 +44,7 @@ private void OnTransferCommand(UInt160 tokenHash, UInt160 to, decimal amount, UI
Transaction tx;
try
{
tx = CurrentWallet.MakeTransaction(snapshot, new[]
tx = CurrentWallet!.MakeTransaction(snapshot, new[]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With nullable enabled, NoWallet would be unnecessary.

Copy link
Member

@cschuchardt88 cschuchardt88 Dec 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You shouldn't do ! unless 100% sure its not going to be null. Set tx to nullable like Transaction? tx;. then check for null. That's the point of nullable. If you don't want it to be nullable than check return for null, and you dont have to use !. Also another point of nullable is for you to be checking for null.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also the reason why you are getting the warning for nullable is because your not doing null checking. For example if (tx == null).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With noWallet you can use !

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With nullable enabled, NoWallet would be unnecessary.

How?

{
new TransferOutput
{
Expand Down
1 change: 0 additions & 1 deletion src/Neo.CLI/CLI/MainService.Native.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

using Neo.ConsoleService;
using Neo.SmartContract.Native;
using System;
using System.Linq;

namespace Neo.CLI
Expand Down
29 changes: 15 additions & 14 deletions src/Neo.CLI/CLI/MainService.Plugins.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,26 +72,27 @@ private async Task<MemoryStream> DownloadPluginAsync(string pluginName)
if (response.StatusCode == HttpStatusCode.NotFound)
{
response.Dispose();
Version versionCore = typeof(Plugin).Assembly.GetName().Version;
Version versionCore = typeof(Plugin).Assembly.GetName().Version!;
HttpRequestMessage request = new(HttpMethod.Get,
"https://api.github.com/repos/neo-project/neo-modules/releases");
request.Headers.UserAgent.ParseAdd(
$"{GetType().Assembly.GetName().Name}/{GetType().Assembly.GetVersion()}");
using HttpResponseMessage responseApi = await http.SendAsync(request);
byte[] buffer = await responseApi.Content.ReadAsByteArrayAsync();
var releases = JObject.Parse(buffer);
var asset = ((JArray)releases)
.Where(p => !p["tag_name"].GetString().Contains('-'))
if (JToken.Parse(buffer) is not JArray arr) throw new Exception("Plugin doesn't exist.");
var asset = arr
.Where(p => p?["tag_name"] is not null && p?["assets"] is not null)
.Where(p => !p!["tag_name"]!.GetString().Contains('-'))
.Select(p => new
{
Version = Version.Parse(p["tag_name"].GetString().TrimStart('v')),
Assets = (JArray)p["assets"]
Version = Version.Parse(p!["tag_name"]!.GetString().TrimStart('v')),
Assets = p["assets"] as JArray
})
.OrderByDescending(p => p.Version)
.First(p => p.Version <= versionCore).Assets
.FirstOrDefault(p => p["name"].GetString() == $"{pluginName}.zip");
.First(p => p.Version <= versionCore).Assets?
.FirstOrDefault(p => p?["name"]?.GetString() == $"{pluginName}.zip");
if (asset is null) throw new Exception("Plugin doesn't exist.");
response = await http.GetAsync(asset["browser_download_url"].GetString());
response = await http.GetAsync(asset["browser_download_url"]?.GetString());
}

using (response)
Expand Down Expand Up @@ -121,7 +122,7 @@ private async Task<MemoryStream> DownloadPluginAsync(string pluginName)
/// <param name="pluginName">Name of the plugin</param>
/// <param name="installed">Dependency set</param>
/// <param name="overWrite">Install by force for `update`</param>
private async Task InstallPluginAsync(string pluginName, HashSet<string> installed = null,
private async Task InstallPluginAsync(string pluginName, HashSet<string>? installed = null,
bool overWrite = false)
{
installed ??= new HashSet<string>();
Expand All @@ -135,7 +136,7 @@ private async Task InstallPluginAsync(string pluginName, HashSet<string> install
}

using ZipArchive zip = new(stream, ZipArchiveMode.Read);
ZipArchiveEntry entry = zip.Entries.FirstOrDefault(p => p.Name == "config.json");
ZipArchiveEntry? entry = zip.Entries.FirstOrDefault(p => p.Name == "config.json");
if (entry is not null)
{
await using Stream es = entry.Open();
Expand All @@ -160,10 +161,10 @@ private async Task InstallDependenciesAsync(Stream config, HashSet<string> insta
var dependencies = dependency.GetChildren().Select(p => p.Get<string>()).ToArray();
if (dependencies.Length == 0) return;

foreach (string plugin in dependencies.Where(p => !PluginExists(p)))
foreach (string? plugin in dependencies.Where(p => p is not null && !PluginExists(p)))
{
ConsoleHelper.Info($"Installing dependency: {plugin}");
await InstallPluginAsync(plugin, installed);
await InstallPluginAsync(plugin!, installed);
}
}

Expand Down Expand Up @@ -201,7 +202,7 @@ private void OnUnInstallCommand(string pluginName)
.GetSection("Dependency")
.GetChildren()
.Select(d => d.Get<string>())
.Any(v => v.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase)))
.Any(v => v is not null && v.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase)))
{
ConsoleHelper.Error(
$"Can not uninstall. Other plugins depend on this plugin, try `reinstall {pluginName}` if the plugin is broken.");
Expand Down
Loading