|
| 1 | +using System.Diagnostics.CodeAnalysis; |
| 2 | + |
| 3 | +namespace TonLibDotNet.Utils |
| 4 | +{ |
| 5 | + public class AddressUtils |
| 6 | + { |
| 7 | + public static readonly AddressUtils Instance = new (); |
| 8 | + |
| 9 | + public const byte BasechainId = AddressValidator.BasechainId; |
| 10 | + public const byte MasterchainId = AddressValidator.MasterchainId; |
| 11 | + |
| 12 | + /// <summary> |
| 13 | + /// Checks if provided 'address' is valid (including checksum check), return |
| 14 | + /// </summary> |
| 15 | + /// <param name="address">Address to check.</param> |
| 16 | + /// <param name="workchainId">After successful validation contains 'Workchain ID' of address (compare with <see cref="BasechainId"/> or <see cref="MasterchainId"/>).</param> |
| 17 | + /// <param name="bounceable">After successful validation contains 'Bounceable' flag of address.</param> |
| 18 | + /// <param name="testnetOnly">After successful validation contains 'TestnetOnly' flag of address.</param> |
| 19 | + /// <returns>Returns <b>true</b> if address is valid, and <b>false</b> otherwise.</returns> |
| 20 | + /// <exception cref="ArgumentNullException">When 'address' is null or empty string.</exception> |
| 21 | + public bool IsValid([NotNullWhen(true)] string address, out byte workchainId, out bool bounceable, out bool testnetOnly) |
| 22 | + { |
| 23 | + return AddressValidator.TryParseAddress(address, out workchainId, out _, out bounceable, out testnetOnly, out _); |
| 24 | + } |
| 25 | + |
| 26 | + /// <summary> |
| 27 | + /// Updates address (if needed): sets 'bounceable' flag to required value. |
| 28 | + /// </summary> |
| 29 | + /// <param name="address">Address to convert.</param> |
| 30 | + /// <param name="bounceable">Required value of 'bounceable' flag.</param> |
| 31 | + /// <returns>Returns updated address (with flag changed). Returns original one when flag has already been equal to required value.</returns> |
| 32 | + /// <exception cref="ArgumentException">When 'address' is not valid (<see cref="IsValid"/>).</exception> |
| 33 | + /// <exception cref="ArgumentNullException">When 'address' is null or empty string.</exception> |
| 34 | + public string SetBounceable(string address, bool bounceable) |
| 35 | + { |
| 36 | + if (!AddressValidator.TryParseAddress(address, out var workchainId, out var accountId, out var bounceableOld, out var testnetOnly, out var urlSafe)) |
| 37 | + { |
| 38 | + throw new ArgumentException("Invalid address", nameof(address)); |
| 39 | + } |
| 40 | + |
| 41 | + return bounceable == bounceableOld ? address : AddressValidator.MakeAddress(workchainId, accountId, bounceable, testnetOnly, urlSafe); |
| 42 | + } |
| 43 | + } |
| 44 | +} |
0 commit comments