Skip to content

Commit

Permalink
Add API methods 'failtrade', 'unfailtrade'
Browse files Browse the repository at this point in the history
Prerequisite for next PR: Add API method 'gettrades'

The `gettrades` method will show 'open', 'closed', and 'failed' trades.
Users already needed to be able to fail and unfail trades for the
same reasons they do in the UI.  API test cases will need to be able to
fail and unfail trades to check correct behavior of 'gettrades' method.

Based on branch `rename-keepfunds2closetrade`.
  • Loading branch information
ghubstan committed Jan 7, 2022
1 parent 905841b commit 7690ffd
Show file tree
Hide file tree
Showing 14 changed files with 452 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

import org.slf4j.Logger;

import lombok.Getter;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInfo;

Expand Down Expand Up @@ -36,6 +38,7 @@ public class AbstractTradeTest extends AbstractOfferTest {
public static final ExpectedProtocolStatus EXPECTED_PROTOCOL_STATUS = new ExpectedProtocolStatus();

// A Trade ID cache for use in @Test sequences.
@Getter
protected static String tradeId;

protected final Supplier<Integer> maxTradeStateAndPhaseChecks = () -> isLongRunningTest ? 10 : 2;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*
* This file is part of Bisq.
*
* Bisq is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at
* your option) any later version.
*
* Bisq is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
* License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Bisq. If not, see <http://www.gnu.org/licenses/>.
*/

package bisq.apitest.method.trade;

import io.grpc.StatusRuntimeException;

import lombok.extern.slf4j.Slf4j;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.TestMethodOrder;

import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;



import bisq.apitest.method.offer.AbstractOfferTest;

@Disabled
@Slf4j
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class FailUnfailTradeTest extends AbstractTradeTest {

@BeforeAll
public static void setUp() {
AbstractOfferTest.setUp();
}

@BeforeEach
public void init() {
EXPECTED_PROTOCOL_STATUS.init();
}


@Test
@Order(1)
public void testFailAndUnFailBuyBTCTrade(final TestInfo testInfo) {
TakeBuyBTCOfferTest test = new TakeBuyBTCOfferTest();
test.testTakeAlicesBuyOffer(testInfo);

var tradeId = test.getTradeId();
aliceClient.failTrade(tradeId);

Throwable exception = assertThrows(StatusRuntimeException.class, () -> aliceClient.getTrade(tradeId));
String expectedExceptionMessage = format("INVALID_ARGUMENT: trade with id '%s' not found", tradeId);
assertEquals(expectedExceptionMessage, exception.getMessage());

try {
aliceClient.unFailTrade(tradeId);
aliceClient.getTrade(tradeId); //Throws ex if trade is still failed.
} catch (Exception ex) {
fail(ex);
}
}

@Test
@Order(2)
public void testFailAndUnFailSellBTCTrade(final TestInfo testInfo) {
TakeSellBTCOfferTest test = new TakeSellBTCOfferTest();
test.testTakeAlicesSellOffer(testInfo);

var tradeId = test.getTradeId();
aliceClient.failTrade(tradeId);

Throwable exception = assertThrows(StatusRuntimeException.class, () -> aliceClient.getTrade(tradeId));
String expectedExceptionMessage = format("INVALID_ARGUMENT: trade with id '%s' not found", tradeId);
assertEquals(expectedExceptionMessage, exception.getMessage());

try {
aliceClient.unFailTrade(tradeId);
aliceClient.getTrade(tradeId); //Throws ex if trade is still failed.
} catch (Exception ex) {
fail(ex);
}
}

@Test
@Order(3)
public void testFailAndUnFailBuyXmrTrade(final TestInfo testInfo) {
TakeBuyXMROfferTest test = new TakeBuyXMROfferTest();
test.createXmrPaymentAccounts();
test.testTakeAlicesSellBTCForXMROffer(testInfo);

var tradeId = test.getTradeId();
aliceClient.failTrade(tradeId);

Throwable exception = assertThrows(StatusRuntimeException.class, () -> aliceClient.getTrade(tradeId));
String expectedExceptionMessage = format("INVALID_ARGUMENT: trade with id '%s' not found", tradeId);
assertEquals(expectedExceptionMessage, exception.getMessage());

try {
aliceClient.unFailTrade(tradeId);
aliceClient.getTrade(tradeId); //Throws ex if trade is still failed.
} catch (Exception ex) {
fail(ex);
}
}

@Test
@Order(4)
public void testFailAndUnFailTakeSellXMRTrade(final TestInfo testInfo) {
TakeSellXMROfferTest test = new TakeSellXMROfferTest();
test.createXmrPaymentAccounts();
test.testTakeAlicesBuyBTCForXMROffer(testInfo);

var tradeId = test.getTradeId();
aliceClient.failTrade(tradeId);

Throwable exception = assertThrows(StatusRuntimeException.class, () -> aliceClient.getTrade(tradeId));
String expectedExceptionMessage = format("INVALID_ARGUMENT: trade with id '%s' not found", tradeId);
assertEquals(expectedExceptionMessage, exception.getMessage());

try {
aliceClient.unFailTrade(tradeId);
aliceClient.getTrade(tradeId); //Throws ex if trade is still failed.
} catch (Exception ex) {
fail(ex);
}
}
}
11 changes: 11 additions & 0 deletions apitest/src/test/java/bisq/apitest/scenario/TradeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

import bisq.apitest.method.trade.AbstractTradeTest;
import bisq.apitest.method.trade.BsqSwapTradeTest;
import bisq.apitest.method.trade.FailUnfailTradeTest;
import bisq.apitest.method.trade.TakeBuyBSQOfferTest;
import bisq.apitest.method.trade.TakeBuyBTCOfferTest;
import bisq.apitest.method.trade.TakeBuyBTCOfferWithNationalBankAcctTest;
Expand Down Expand Up @@ -130,4 +131,14 @@ public void testBsqSwapTradeTest(final TestInfo testInfo) {
test.testBobTakesBsqSwapOffer();
test.testGetBalancesAfterTrade();
}

@Test
@Order(9)
public void testFailUnfailTrade(final TestInfo testInfo) {
FailUnfailTradeTest test = new FailUnfailTradeTest();
test.testFailAndUnFailBuyBTCTrade(testInfo);
test.testFailAndUnFailSellBTCTrade(testInfo);
test.testFailAndUnFailBuyXmrTrade(testInfo);
test.testFailAndUnFailTakeSellXMRTrade(testInfo);
}
}
26 changes: 26 additions & 0 deletions cli/src/main/java/bisq/cli/CliMain.java
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,28 @@ public static void run(String[] args) {
paymentMethods.forEach(p -> out.println(p.getId()));
return;
}
case failtrade: {
var opts = new GetTradeOptionParser(args).parse();
if (opts.isForHelp()) {
out.println(client.getMethodHelp(method));
return;
}
var tradeId = opts.getTradeId();
client.failTrade(tradeId);
out.printf("open trade %s changed to failed trade%n", tradeId);
return;
}
case unfailtrade: {
var opts = new GetTradeOptionParser(args).parse();
if (opts.isForHelp()) {
out.println(client.getMethodHelp(method));
return;
}
var tradeId = opts.getTradeId();
client.unFailTrade(tradeId);
out.printf("failed trade %s changed to open trade%n", tradeId);
return;
}
case getpaymentacctform: {
var opts = new GetPaymentAcctFormOptionParser(args).parse();
if (opts.isForHelp()) {
Expand Down Expand Up @@ -870,6 +892,10 @@ private static void printHelp(OptionParser parser, @SuppressWarnings("SameParame
"Withdraw received trade funds to external wallet address");
stream.format(rowFormat, "", "[--memo=<\"memo\">]", "");
stream.println();
stream.format(rowFormat, failtrade.name(), "--trade-id=<trade-id>", "Change open trade to failed trade");
stream.println();
stream.format(rowFormat, unfailtrade.name(), "--trade-id=<trade-id>", "Change failed trade to open trade");
stream.println();
stream.format(rowFormat, getpaymentmethods.name(), "", "Get list of supported payment account method ids");
stream.println();
stream.format(rowFormat, getpaymentacctform.name(), "--payment-method-id=<payment-method-id>", "Get a new payment account form");
Expand Down
8 changes: 8 additions & 0 deletions cli/src/main/java/bisq/cli/GrpcClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,14 @@ public void withdrawFunds(String tradeId, String address, String memo) {
tradesServiceRequest.withdrawFunds(tradeId, address, memo);
}

public void failTrade(String tradeId) {
tradesServiceRequest.failTrade(tradeId);
}

public void unFailTrade(String tradeId) {
tradesServiceRequest.unFailTrade(tradeId);
}

public List<PaymentMethod> getPaymentMethods() {
return paymentAccountsServiceRequest.getPaymentMethods();
}
Expand Down
2 changes: 2 additions & 0 deletions cli/src/main/java/bisq/cli/Method.java
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public enum Method {
getpaymentaccts,
getpaymentmethods,
gettrade,
failtrade,
unfailtrade,
gettransaction,
gettxfeerate,
getunusedbsqaddress,
Expand Down
18 changes: 18 additions & 0 deletions cli/src/main/java/bisq/cli/request/TradesServiceRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@
import bisq.proto.grpc.CloseTradeRequest;
import bisq.proto.grpc.ConfirmPaymentReceivedRequest;
import bisq.proto.grpc.ConfirmPaymentStartedRequest;
import bisq.proto.grpc.FailTradeRequest;
import bisq.proto.grpc.GetTradeRequest;
import bisq.proto.grpc.TakeOfferReply;
import bisq.proto.grpc.TakeOfferRequest;
import bisq.proto.grpc.TradeInfo;
import bisq.proto.grpc.UnFailTradeRequest;
import bisq.proto.grpc.WithdrawFundsRequest;


Expand Down Expand Up @@ -103,4 +105,20 @@ public void withdrawFunds(String tradeId, String address, String memo) {
//noinspection ResultOfMethodCallIgnored
grpcStubs.tradesService.withdrawFunds(request);
}

public void failTrade(String tradeId) {
var request = FailTradeRequest.newBuilder()
.setTradeId(tradeId)
.build();
//noinspection ResultOfMethodCallIgnored
grpcStubs.tradesService.failTrade(request);
}

public void unFailTrade(String tradeId) {
var request = UnFailTradeRequest.newBuilder()
.setTradeId(tradeId)
.build();
//noinspection ResultOfMethodCallIgnored
grpcStubs.tradesService.unFailTrade(request);
}
}
8 changes: 8 additions & 0 deletions core/src/main/java/bisq/core/api/CoreApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,14 @@ public String getBsqSwapTradeRole(BsqSwapTrade bsqSwapTrade) {
return coreTradesService.getBsqSwapTradeRole(bsqSwapTrade);
}

public void failTrade(String tradeId) {
coreTradesService.failTrade(tradeId);
}

public void unFailTrade(String tradeId) {
coreTradesService.unFailTrade(tradeId);
}

///////////////////////////////////////////////////////////////////////////////////////////
// Wallets
///////////////////////////////////////////////////////////////////////////////////////////
Expand Down
61 changes: 61 additions & 0 deletions core/src/main/java/bisq/core/api/CoreTradesService.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import bisq.core.offer.bsq_swap.BsqSwapTakeOfferModel;
import bisq.core.trade.ClosedTradableManager;
import bisq.core.trade.TradeManager;
import bisq.core.trade.bisq_v1.FailedTradesManager;
import bisq.core.trade.bisq_v1.TradeResultHandler;
import bisq.core.trade.bisq_v1.TradeUtil;
import bisq.core.trade.model.Tradable;
Expand Down Expand Up @@ -63,6 +64,7 @@ class CoreTradesService {
private final BtcWalletService btcWalletService;
private final OfferUtil offerUtil;
private final ClosedTradableManager closedTradableManager;
private final FailedTradesManager failedTradesManager;
private final TakeOfferModel takeOfferModel;
private final BsqSwapTakeOfferModel bsqSwapTakeOfferModel;
private final TradeManager tradeManager;
Expand All @@ -75,6 +77,7 @@ public CoreTradesService(CoreContext coreContext,
BtcWalletService btcWalletService,
OfferUtil offerUtil,
ClosedTradableManager closedTradableManager,
FailedTradesManager failedTradesManager,
TakeOfferModel takeOfferModel,
BsqSwapTakeOfferModel bsqSwapTakeOfferModel,
TradeManager tradeManager,
Expand All @@ -85,6 +88,7 @@ public CoreTradesService(CoreContext coreContext,
this.btcWalletService = btcWalletService;
this.offerUtil = offerUtil;
this.closedTradableManager = closedTradableManager;
this.failedTradesManager = failedTradesManager;
this.takeOfferModel = takeOfferModel;
this.bsqSwapTakeOfferModel = bsqSwapTakeOfferModel;
this.tradeManager = tradeManager;
Expand Down Expand Up @@ -269,6 +273,37 @@ Trade getTrade(String tradeId) {
));
}

void failTrade(String tradeId) {
// TODO Recommend that API users should use this method with extra care because
// the API lacks methods for diagnosing trade problems, and does not support
// interaction with mediators. Users may accidentally fail valid trades,
// although they can easily be un-failed with the 'unfailtrade' method.
// The 'failtrade' and 'unfailtrade' methods are implemented at this early
// stage of API development to help efficiently test a new
// 'gettrades --category=<open|closed|failed>'
// method currently in development.
coreWalletsService.verifyWalletsAreAvailable();
coreWalletsService.verifyEncryptedWalletIsUnlocked();

var trade = getTrade(tradeId);
tradeManager.onMoveInvalidTradeToFailedTrades(trade);
log.info("Trade {} changed to failed trade.", tradeId);
}

void unFailTrade(String tradeId) {
coreWalletsService.verifyWalletsAreAvailable();
coreWalletsService.verifyEncryptedWalletIsUnlocked();

failedTradesManager.getTradeById(tradeId).ifPresentOrElse(failedTrade -> {
verifyCanUnfailTrade(failedTrade);
failedTradesManager.removeTrade(failedTrade);
tradeManager.addFailedTradeToPendingTrades(failedTrade);
log.info("Failed trade {} changed to open trade.", tradeId);
}, () -> {
throw new IllegalArgumentException(format("failed trade '%s' not found", tradeId));
});
}

private Optional<Trade> getOpenTrade(String tradeId) {
return tradeManager.getTradeById(tradeId);
}
Expand Down Expand Up @@ -318,4 +353,30 @@ private void verifyFundsNotWithdrawn(AddressEntry fromAddressEntry) {
throw new IllegalStateException(format("funds already withdrawn from address '%s'",
fromAddressEntry.getAddressString()));
}

// Throws a RuntimeException if failed trade cannot be changed to OPEN for any reason.
private void verifyCanUnfailTrade(Trade failedTrade) {
if (tradeUtil.getTradeAddresses(failedTrade) == null)
throw new IllegalStateException(
format("cannot change failed trade to open because no trade addresses found for '%s'",
failedTrade.getId()));

if (!failedTradesManager.hasDepositTx(failedTrade))
throw new IllegalStateException(
format("cannot change failed trade to open, no deposit tx found for '%s'",
failedTrade.getId()));

if (!failedTradesManager.hasDelayedPayoutTxBytes(failedTrade))
throw new IllegalStateException(
format("cannot change failed trade to open, no delayed payout tx found for '%s'",
failedTrade.getId()));

failedTradesManager.getBlockingTradeIds(failedTrade).ifPresent(tradeIds -> {
throw new IllegalStateException(
format("cannot change failed trade '%s' to open at this time,"
+ "%ntry again after completing trade(s):%n\t%s",
failedTrade.getId(),
String.join(", ", tradeIds)));
});
}
}
Loading

0 comments on commit 7690ffd

Please sign in to comment.