Skip to content
This repository has been archived by the owner on Nov 24, 2020. It is now read-only.

Commit

Permalink
Support trade type === BUY (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiero authored Apr 29, 2020
1 parent f1633b7 commit c495f2d
Show file tree
Hide file tree
Showing 3 changed files with 483 additions and 387 deletions.
37 changes: 27 additions & 10 deletions src/services/tradeService.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import grpc from 'grpc';
import { Swap, calculateExpectedAmount } from 'tdex-sdk';
import {
Swap,
calculateExpectedAmount,
calculateProposeAmount,
} from 'tdex-sdk';

import {
Balance,
Expand Down Expand Up @@ -111,6 +115,7 @@ class Trade {
let quoteAsset = undefined;
try {
const market = call.request.getMarket();
const tradeType = call.request.getType();
const swapRequestMessage = call.request.getSwapRequest();
if (!market || !swapRequestMessage)
throw {
Expand Down Expand Up @@ -147,16 +152,28 @@ class Trade {
);
const balanceP = balances[assetP];
const balanceR = balances[assetR];
const expectedAmount = calculateExpectedAmount(
balanceP,
balanceR,
amountP,
marketFound.fee
);

//TODO Here we need to take into account a little slippage so the check need to be a range between a min and max spread
if (expectedAmount !== amountR)
throw new Error('Not valid amount_r for the proposed amount_p');
if (tradeType === TradeProposeRequest.Type.BUY) {
const proposeAmount = calculateProposeAmount(
balanceP,
balanceR,
amountR,
marketFound.fee
);
// TODO check possible slippage due network congestion
if (proposeAmount !== amountP)
throw new Error('Not valid amount_p for the requested amount_r');
} else {
const expectedAmount = calculateExpectedAmount(
balanceP,
balanceR,
amountP,
marketFound.fee
);
//TODO Here we need to take into account a little slippage so the check need to be a range between a min and max spread
if (expectedAmount !== amountR)
throw new Error('Not valid amount_r for the proposed amount_p');
}

// Let's stop the market to not process other concurrent swaps
await marketModel.updateMarket({ quoteAsset }, { tradable: false });
Expand Down
67 changes: 65 additions & 2 deletions test/e2e.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { sleep, faucet, mint, fetchUtxos } from './helpers';
import { networks } from 'liquidjs-lib';
import { markets, balances, tradePropose, tradeComplete } from './grpc/trader';
import Wallet, { fromWIF, WalletInterface } from '../src/components/wallet';
import { Swap, calculateExpectedAmount } from 'tdex-sdk';
import {
Swap,
calculateExpectedAmount,
calculateProposeAmount,
} from 'tdex-sdk';
import { SwapAccept } from 'tdex-protobuf/js/swap_pb';

describe('End to end testing', () => {
Expand Down Expand Up @@ -119,7 +123,66 @@ describe('End to end testing', () => {
// check if market got back to be tradabale
const tradableMarketsAgain = await markets();
expect(tradableMarketsAgain.length).toStrictEqual(1);
}, 35000);

/**
* Now let's try to BUY
*/

const balancesAndFee2 = await balances({ baseAsset, quoteAsset });
const amountToReceive2 = 5000;
const amountToBeSent2 = calculateProposeAmount(
balancesAndFee2.balances[quoteAsset],
balancesAndFee2.balances[baseAsset],
amountToReceive2,
balancesAndFee.fee
);
const traderUtxos2 = await fetchUtxos(traderWallet.address, USDT);
const emptyPsbt2 = Wallet.createTx();
const psbt2 = traderWallet.updateTx(
emptyPsbt2,
traderUtxos2,
amountToBeSent2,
amountToReceive2,
USDT,
LBTC
);
const swap2 = new Swap({ chain: 'regtest' });
const swapRequestSerialized2 = swap2.request({
assetToBeSent: USDT,
amountToBeSent: amountToBeSent2,
assetToReceive: LBTC,
amountToReceive: amountToReceive2,
psbtBase64: psbt2,
});
// 0 === Buy === receiving base_asset; 1 === sell === receiving quote_asset
const tradeType2 = 0;
const swapAcceptSerialized2: Uint8Array = await tradePropose(
market,
tradeType2,
swapRequestSerialized2
);

// trader need to check the signed inputs by the provider
// and add his own inputs if all is correct
const swapAcceptMessage2 = SwapAccept.deserializeBinary(
swapAcceptSerialized2
);
const transaction2 = swapAcceptMessage2.getTransaction();
const signedPsbt2 = traderWallet.sign(transaction2);

// Trader adds his signed inputs to the transaction
const swapCompleteSerialized2 = swap2.complete({
message: swapAcceptSerialized2,
psbtBase64: signedPsbt2,
});

// Trader call the tradeComplete endpoint to finalize the swap
const txid2 = await tradeComplete(swapCompleteSerialized2);
expect(txid2).toBeDefined();
// check if market got back to be tradabale
const tradableMarketsAgain2 = await markets();
expect(tradableMarketsAgain2.length).toStrictEqual(1);
}, 55000);

test('Calculate expected amount', () => {
// balanceP, balanceR, amountP, fee
Expand Down
Loading

0 comments on commit c495f2d

Please sign in to comment.