Skip to content

Commit 3e44b68

Browse files
committed
feature(cmd): optimize details
1 parent 02605b3 commit 3e44b68

File tree

8 files changed

+188
-57
lines changed

8 files changed

+188
-57
lines changed

README.md

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ For more information on a specific command, just type the command in the termina
122122
| [GetMarketPriceByPair](#How-to-use-tron-dex-to-sell-asset) | [GetMemoFee](#Get-resource-prices-and-memo-fee) | [GetNextMaintenanceTime](#Some-others) |
123123
| [GetProposal](#Obtain-proposal-information) | [GetReward](#Brokerage) | [GetTransactionApprovedList](#How-to-use-the-multi-signature-feature-of-wallet-cli) |
124124
| [GetTransactionById](#How-to-get-transaction-information) | [GetTransactionCountByBlockNum](#How-to-get-transaction-information) | [GetTransactionInfoByBlockNum](#How-to-get-transaction-information) |
125-
| [GetTransactionInfoById](#How-to-get-transaction-information) | [GetTransactionSignWeight](#How-to-use-the-multi-signature-feature-of-wallet-cli) | [GetUsdtBalance](#get-usdt-balance) |
125+
| [GetTransactionInfoById](#How-to-get-transaction-information) | [GetTransactionSignWeight](#How-to-use-the-multi-signature-feature-of-wallet-cli) | [GetUSDTBalance](#get-usdt-balance) |
126126
| [GetUsdtTransferById](#get-usdt-transfer-by-id) | [ImportWallet](#Wallet-related-commands) | [ImportWalletByBase64](#Wallet-related-commands) |
127127
| [ImportWalletByKeystore](#export-import-wallet-keystore) | [ImportWalletByLedger](#import-wallet-by-ledger) | [ImportWalletByMnemonic](#import-and-export-mnemonic) |
128128
| [ListAssetIssue](#How-to-obtain-trc10-token-information) | [ListAssetIssuePaginated](#list-asset-issue-paginated) | [ListExchanges](#How-to-trade-on-the-exchange) |
@@ -786,7 +786,7 @@ three types of accesses:
786786
The rest of the users will be granted
787787

788788
```console
789-
> Updateaccountpermission TRGhNNfnmgLegT4zHNjEqDSADjgmnHvubJ {"owner_permission":{"type":0,"permission_name":"owner","threshold":1,"keys":[{"address":"TRGhNNfnmgLegT4zHNjEqDSADjgmnHvubJ","weight":1}]},"witness_permission":{"type":1,"permission_name":"owner","threshold":1,"keys":[{"address":"TRGhNNfnmgLegT4zHNjEqDSADjgmnHvubJ","weight":1}]},"active_permissions":[{"type":2,"permission_name":"active12323","threshold":2,"operations":"7fff1fc0033e0000000000000000000000000000000000000000000000000000","keys":[{"address":"TNhXo1GbRNCuorvYu5JFWN3m2NYr9QQpVR","weight":1},{"address":"TKwhcDup8L2PH5r6hxp5CQvQzZqJLmKvZP","weight":1}]}]}
789+
> Updateaccountpermission TRGhNNfnmgLegT4zHNjEqDSADjgmnHvubJ {"owner_permission":{"type":0,"permission_name":"owner","threshold":1,"keys":[{"address":"TRGhNNfnmgLegT4zHNjEqDSADjgmnHvubJ","weight":1}]},"witness_permission":{"type":1,"permission_name":"witness","threshold":1,"keys":[{"address":"TRGhNNfnmgLegT4zHNjEqDSADjgmnHvubJ","weight":1}]},"active_permissions":[{"type":2,"permission_name":"active12323","threshold":2,"operations":"7fff1fc0033e0000000000000000000000000000000000000000000000000000","keys":[{"address":"TNhXo1GbRNCuorvYu5JFWN3m2NYr9QQpVR","weight":1},{"address":"TKwhcDup8L2PH5r6hxp5CQvQzZqJLmKvZP","weight":1}]}]}
790790
```
791791
or
792792
```console
@@ -2502,9 +2502,10 @@ wallet> ShowReceivingQrCode
25022502
████ █▄▄▄█ █ ▀█▀█▄█▄▀▀█▄ ▄█ ██▀▄████
25032503
████▄▄▄▄▄▄▄█▄▄██▄██ ▀▀▄▄▄▄█ ▀ ████
25042504
█████████████████████████████████████
2505+
TEDapYSVvAZ3aYH7w8N9tMEEFKaNKUD5Bp
25052506
```
25062507
### get usdt balance
2507-
> GetUsdtBalance
2508+
> GetUSDTBalance
25082509
25092510
Get the current USDT balance of the account.
25102511

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package org.tron.common.utils;
2+
3+
import org.jline.reader.Candidate;
4+
import org.jline.reader.Completer;
5+
import org.jline.reader.LineReader;
6+
import org.jline.reader.ParsedLine;
7+
8+
import java.util.List;
9+
import java.util.Locale;
10+
11+
public class CaseInsensitiveCommandCompleter implements Completer {
12+
13+
private final String[] commands;
14+
15+
public CaseInsensitiveCommandCompleter(String... commands) {
16+
this.commands = commands;
17+
}
18+
19+
@Override
20+
public void complete(LineReader reader, ParsedLine line, List<Candidate> candidates) {
21+
String buffer = line.word().toLowerCase(Locale.ROOT);
22+
23+
for (String cmd : commands) {
24+
if (cmd.toLowerCase(Locale.ROOT).startsWith(buffer)) {
25+
candidates.add(new Candidate(
26+
cmd,
27+
cmd,
28+
null,
29+
null,
30+
null,
31+
null,
32+
true
33+
));
34+
}
35+
}
36+
}
37+
}
38+

src/main/java/org/tron/core/manager/UpdateAccountPermissionInteractive.java

Lines changed: 62 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package org.tron.core.manager;
22

3+
import static org.apache.commons.lang3.StringUtils.EMPTY;
34
import static org.tron.common.utils.ByteUtil.hexStringToIntegerList;
45
import static org.tron.common.utils.ByteUtil.integerListToHexString;
56
import static org.tron.common.utils.Utils.greenBoldHighlight;
@@ -19,6 +20,7 @@
1920
import java.util.Scanner;
2021
import java.util.Set;
2122
import java.util.stream.Collectors;
23+
import java.util.stream.IntStream;
2224
import lombok.Getter;
2325
import lombok.Setter;
2426
import org.bouncycastle.util.encoders.Hex;
@@ -38,8 +40,8 @@ public class UpdateAccountPermissionInteractive {
3840
);
3941
private static final List<Integer> AVAILABLE_OPERATIONS = Arrays.asList(
4042
0, 1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13,
41-
14, 15, 16, 17, 18, 30, 31, 33,
42-
41, 42, 43, 44, 45, 46, 48, 49, 54,
43+
14, 15, 16, 17, 18, 19, 30, 31, 33,
44+
41, 42, 43, 44, 45, 46, 48, 49, 52, 53, 54,
4345
55, 56, 57, 58, 59
4446
);
4547
private static final Map<String, String> operationsMap = new HashMap<>();
@@ -62,6 +64,7 @@ public class UpdateAccountPermissionInteractive {
6264
operationsMap.put("16", "Create Proposal");
6365
operationsMap.put("17", "Approve Proposal");
6466
operationsMap.put("18", "Cancel Proposal");
67+
operationsMap.put("19", "Set Account Id");
6568
operationsMap.put("30", "Create Smart Contract");
6669
operationsMap.put("31", "Trigger Smart Contract");
6770
operationsMap.put("33", "Update Contract Parameters");
@@ -73,6 +76,8 @@ public class UpdateAccountPermissionInteractive {
7376
operationsMap.put("46", "Update Account Permissions");
7477
operationsMap.put("48", "Clear Contract ABI");
7578
operationsMap.put("49", "Update SR Commission Ratio");
79+
operationsMap.put("52", "Market Sell Asset");
80+
operationsMap.put("53", "Market Cancel Order");
7681
operationsMap.put("54", "TRX Stake (2.0)");
7782
operationsMap.put("55", "TRX Unstake (2.0)");
7883
operationsMap.put("56", "Withdraw Unstaked TRX");
@@ -124,7 +129,11 @@ public String start(String address) {
124129
deleteActivePermission();
125130
break;
126131
case "6":
127-
return showFinalSummary();
132+
String result = showFinalSummary();
133+
if (!result.isEmpty()) {
134+
return result;
135+
}
136+
break;
128137
case "7":
129138
System.out.println("Exiting interactive mode.");
130139
throw new IllegalArgumentException("Already exited interactive mode.");
@@ -220,6 +229,10 @@ private void editKeys(Permission permission) {
220229
System.out.println("Each active permission can only add 5 addresses at most.");
221230
continue;
222231
}
232+
if (permission.getType() == 1) {
233+
System.out.println("Witness permission's key count should be 1, adding keys is not allowed");
234+
continue;
235+
}
223236
System.out.print("Enter key(Authorized To) address (or 'q' to cancel): ");
224237
String addr = scanner.nextLine().trim();
225238
if ("q".equalsIgnoreCase(addr)) continue;
@@ -248,7 +261,16 @@ private void editKeys(Permission permission) {
248261
continue;
249262
}
250263

264+
long totalWeight = permission.getKeys().stream()
265+
.mapToLong(Key::getWeight)
266+
.sum();
267+
if (totalWeight + weight < permission.getThreshold()) {
268+
System.out.println(redBoldHighlight("The sum of address weights must be greater than or equal to the threshold"));
269+
continue;
270+
}
271+
251272
permission.getKeys().add(new Key(addr, weight));
273+
252274
System.out.println("Added key: " + addr + " (weight=" + weight + ")");
253275

254276
break;
@@ -288,8 +310,17 @@ private void editKeys(Permission permission) {
288310
try {
289311
long w = Long.parseLong(newWeight);
290312
long threshold = permission.getThreshold();
313+
List<Key> keys = permission.getKeys();
314+
long remainWeight = IntStream.range(0, keys.size())
315+
.filter(i -> i != midx)
316+
.mapToLong(i -> keys.get(i).getWeight())
317+
.sum();
318+
if (remainWeight + w < permission.getThreshold()) {
319+
System.out.println(redBoldHighlight("The sum of address weights must be greater than or equal to the threshold"));
320+
continue;
321+
}
291322
if (w <= 0 || w > threshold) {
292-
System.out.println("Weight must be >0 and <= threshold(" + threshold + "). Skip changing weight.");
323+
System.out.println("Weight must be > 0 and <= threshold(" + threshold + "). Skip changing weight.");
293324
} else {
294325
keyToEdit.weight = w;
295326
}
@@ -305,6 +336,10 @@ private void editKeys(Permission permission) {
305336

306337
break;
307338
case "3":
339+
if (permission.getType() == 1) {
340+
System.out.println("Witness permission's key count should be 1, deleting keys is not allowed");
341+
continue;
342+
}
308343
if (permission.getKeys().isEmpty()) {
309344
System.out.println("No keys(Authorized To) to delete.");
310345
continue;
@@ -627,6 +662,10 @@ private void deleteActivePermission() {
627662
printPermissionSummary(actives.get(i), i + 1);
628663
System.out.println("---------------------------------------------------");
629664
}
665+
if (actives.size() == 1) {
666+
System.out.println(redBoldHighlight("Currently, there is only one active permission, and deletion is not allowed."));
667+
return;
668+
}
630669
System.out.print("Enter index to delete, Enter " + greenBoldHighlight("b") + " to back: ");
631670
String idxStr = scanner.nextLine().trim();
632671
if ("b".equalsIgnoreCase(idxStr) || "q".equalsIgnoreCase(idxStr)) {
@@ -674,13 +713,27 @@ private void printPermissionSummary(Permission p, int index) {
674713
}
675714

676715
private String showFinalSummary() {
677-
System.out.println("The preview of your updated account permissions is as follows:");
678-
printPermissionData(data);
679-
return JSON.toJSONString(data.toTronJson());
716+
while (true) {
717+
printPermissionData(data);
718+
719+
System.out.print("\nDo you want to proceed with these changes? (Enter " + greenBoldHighlight("y/n") + ", n = return to edit): ");
720+
String input = scanner.nextLine().trim().toLowerCase();
721+
722+
switch (input) {
723+
case "y":
724+
System.out.println("Confirmed. Preparing final JSON...");
725+
return JSON.toJSONString(data.toTronJson());
726+
case "n":
727+
System.out.println("Returning to main menu for further edits...");
728+
return EMPTY;
729+
default:
730+
System.out.println("Invalid input. Please enter" + greenBoldHighlight("y/n"));
731+
}
732+
}
680733
}
681734

682735
private void printPermissionData(PermissionData data) {
683-
System.out.println("\n================ Account Permission Info ================");
736+
System.out.println("\n=============== Preview of Updated Account Permissions ===============\n");
684737

685738
// --- Owner Permission ---
686739
Permission owner = data.getOwnerPermission();
@@ -711,7 +764,7 @@ private void printPermissionData(PermissionData data) {
711764
printPermissionDetail(actives.get(i));
712765
}
713766
}
714-
System.out.println("=========================================================");
767+
System.out.println("=======================================================================");
715768
}
716769

717770
private void printPermissionDetail(Permission p) {

src/main/java/org/tron/walletcli/Client.java

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@
6464
import java.util.stream.Stream;
6565
import org.apache.commons.lang3.ArrayUtils;
6666
import org.apache.commons.lang3.tuple.Pair;
67+
import org.apache.commons.lang3.tuple.Triple;
6768
import org.bouncycastle.util.encoders.Hex;
6869
import org.hid4java.HidDevice;
6970
import org.jline.reader.Candidate;
@@ -85,6 +86,7 @@
8586
import org.tron.common.utils.AbiUtil;
8687
import org.tron.common.utils.ByteArray;
8788
import org.tron.common.utils.ByteUtil;
89+
import org.tron.common.utils.CaseInsensitiveCommandCompleter;
8890
import org.tron.common.utils.PathUtil;
8991
import org.tron.common.utils.Utils;
9092
import org.tron.core.dao.AddressEntry;
@@ -193,7 +195,7 @@ public class Client {
193195
"GetTransactionInfoByBlockNum",
194196
"GetTransactionInfoById",
195197
"GetTransactionSignWeight",
196-
"GetUsdtBalance",
198+
"GetUSDTBalance",
197199
"GetUsdtTransferById",
198200
"Help",
199201
"ImportWallet",
@@ -2877,7 +2879,7 @@ private void triggerContract(String[] parameters)
28772879
byte[] contractAddress = WalletApi.decodeFromBase58Check(contractAddrStr);
28782880

28792881
boolean result = walletApiWrapper.callContract(
2880-
ownerAddress, contractAddress, callValue, input, feeLimit, tokenValue, tokenId, false, false);
2882+
ownerAddress, contractAddress, callValue, input, feeLimit, tokenValue, tokenId, false, false).getLeft();
28812883
if (result) {
28822884
System.out.println("Broadcast the TriggerContract " + successfulHighlight() + ".\n"
28832885
+ "Please check the given transaction id to get the result on blockchain using getTransactionInfoById command");
@@ -3477,6 +3479,7 @@ private void run() {
34773479
System.out.println("Version" + VERSION);
34783480
System.exit(0);
34793481
}
3482+
// Security.addProvider(TronCastleProvider.getInstance());
34803483
System.out.println();
34813484
System.out.println("Welcome to Tron " + blueBoldHighlight("Wallet-Cli"));
34823485
printBanner();
@@ -3497,7 +3500,7 @@ private void run() {
34973500
.dumb(true)
34983501
.nativeSignals(true).build();
34993502
DefaultParser parser = new DefaultParser();
3500-
Completer commandCompleter = new StringsCompleter(commandList);
3503+
Completer commandCompleter = new CaseInsensitiveCommandCompleter(commandList);
35013504
Completer addressCompleter = (reader, line, candidates) -> {
35023505
List<AddressEntry> addressEntries = new AddressBookService().getEntries();
35033506
for (int i = 0; i < addressEntries.size(); i++) {
@@ -3513,13 +3516,13 @@ private void run() {
35133516
));
35143517
}
35153518
};
3516-
Completer completer = new ArgumentCompleter(
3519+
ArgumentCompleter completer = new ArgumentCompleter(
35173520
commandCompleter,
35183521
addressCompleter,
35193522
addressCompleter,
35203523
NullCompleter.INSTANCE
35213524
);
3522-
3525+
completer.setStrict(false);
35233526
LineReader lineReader = LineReaderBuilder.builder()
35243527
.terminal(terminal)
35253528
.parser(parser)
@@ -3722,7 +3725,7 @@ private void run() {
37223725
break;
37233726
}
37243727
case "getusdtbalance": {
3725-
getUsdtBalance(parameters);
3728+
getUSDTBalance(parameters);
37263729
break;
37273730
}
37283731
case "transferasset": {
@@ -4187,7 +4190,7 @@ private void getUsdtTransferById(String[] parameters) throws IOException {
41874190
}
41884191
}
41894192

4190-
private void getUsdtBalance(String[] parameters) throws Exception {
4193+
private void getUSDTBalance(String[] parameters) throws Exception {
41914194
NetType netType = WalletApi.getCurrentNetwork();
41924195
if (netType != MAIN && netType != NILE && netType != SHASTA) {
41934196
System.out.println("This command does not support the current network.");
@@ -4203,16 +4206,16 @@ private void getUsdtBalance(String[] parameters) throws Exception {
42034206
return;
42044207
}
42054208
} else {
4206-
System.out.println("GetUsdtBalance needs no parameter or 1 parameter like the following: ");
4207-
System.out.println("GetUsdtBalance Address ");
4209+
System.out.println("GetUSDTBalance needs no parameter or 1 parameter like the following: ");
4210+
System.out.println("GetUSDTBalance Address ");
42084211
return;
42094212
}
4210-
Pair<Boolean, Long> pair = walletApiWrapper.getUsdtBalance(ownerAddress);
4213+
Triple<Boolean, Long, Long> pair = walletApiWrapper.getUSDTBalance(ownerAddress);
42114214
if (Boolean.TRUE.equals(pair.getLeft())) {
42124215
long balance = pair.getRight();
42134216
System.out.println("USDT balance = " + balance);
42144217
} else {
4215-
System.out.println("GetUsdtBalance " + failedHighlight() + " !!!!");
4218+
System.out.println("GetUSDTBalance " + failedHighlight() + " !!!!");
42164219
}
42174220
}
42184221

@@ -4250,28 +4253,31 @@ private void transferUSDT(String[] parameters) throws Exception {
42504253
System.out.println("Incorrect amount format, please check.");
42514254
}
42524255
// valid amount
4253-
Pair<Boolean, Long> pair = walletApiWrapper.getUsdtBalance(ownerAddress);
4254-
if (Boolean.TRUE.equals(pair.getLeft())) {
4255-
long balance = pair.getRight();
4256+
Triple<Boolean, Long, Long> triple = walletApiWrapper.getUSDTBalance(ownerAddress);
4257+
if (Boolean.TRUE.equals(triple.getLeft())) {
4258+
long balance = triple.getRight();
42564259
if (amount > balance) {
42574260
System.out.println("The usdt balance(" + balance + ") is insufficient.");
42584261
return;
42594262
}
42604263
System.out.println("USDT balance = " + balance);
42614264
} else {
4262-
System.out.println("GetUsdtBalance " + failedHighlight() + " !!!!");
4265+
System.out.println("GetUSDTBalance " + failedHighlight() + " !!!!");
42634266
return;
42644267
}
42654268
String inputStr = String.format("\"%s\",%s", base58ToAddress, amountStr);
42664269
final String methodStr = "transfer(address,uint256)";
42674270
byte[] input = Hex.decode(AbiUtil.parseMethod(methodStr, inputStr, false));
42684271
byte[] contractAddress = WalletApi.decodeFromBase58Check(netType.getUsdtAddress());
42694272
// Estimate bandwidth and energy
4270-
walletApiWrapper.callContract(
4273+
long energyFee = getChainParamValue(walletApiWrapper.getChainParameters(), "getEnergyFee");
4274+
Triple<Boolean, Long, Long> estimateTtriple = walletApiWrapper.callContract(
42714275
ownerAddress, contractAddress, 0, input, 0, 0, "", true, true);
4272-
4276+
long energyUsed = estimateTtriple.getMiddle();
4277+
// The fee limit rises by 20% in the total energy price
4278+
long feeLimit = (long) (energyFee * energyUsed * 1.2);
42734279
boolean result = walletApiWrapper.callContract(
4274-
ownerAddress, contractAddress, 0, input, 1000000000, 0, "", false, false);
4280+
ownerAddress, contractAddress, 0, input, feeLimit, 0, "", false, false).getLeft();
42754281
if (result) {
42764282
System.out.println("Transfer " + amountStr + " to " + base58ToAddress + " broadcast " + successfulHighlight() + ".\n"
42774283
+ "Please check the given transaction id to get the result on blockchain using getTransactionInfoById command.");
@@ -4281,6 +4287,14 @@ private void transferUSDT(String[] parameters) throws Exception {
42814287
askToSaveAddress(base58ToAddress);
42824288
}
42834289

4290+
public static long getChainParamValue(Response.ChainParameters params, String key) {
4291+
return params.getChainParameterList().stream()
4292+
.filter(p -> key.equals(p.getKey()))
4293+
.mapToLong(Response.ChainParameters.ChainParameter::getValue)
4294+
.findFirst()
4295+
.orElseThrow(() -> new IllegalArgumentException("Parameter not found: " + key));
4296+
}
4297+
42844298
private void viewBackupRecords(String[] parameters) {
42854299
if (parameters.length > 0) {
42864300
System.out.println("viewBackupRecords needs no parameters like the following: ");

0 commit comments

Comments
 (0)