Skip to content

Commit

Permalink
fix : nonce and gasPrice in orderFulfilled (#375)
Browse files Browse the repository at this point in the history
* fix nonce and gas in order fulfilled

* resolve UT

* async lock install

* delete comment

Co-authored-by: Hildegard Lydia <[email protected]>
  • Loading branch information
JackyRahman and hilyds authored Jun 6, 2022
1 parent 8cddbb1 commit 9ab8a23
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 34 deletions.
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"@nestjs/typeorm": "^8.0.2",
"@polkadot/api": "^7.8.1",
"@sentry/node": "^6.16.1",
"async-lock": "^1.3.1",
"axios": "^0.21.1",
"axios-mock-adapter": "^1.20.0",
"cache-manager": "^3.4.4",
Expand Down
62 changes: 51 additions & 11 deletions src/common/modules/escrow/escrow.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,29 @@ import { WalletSigner } from 'nestjs-ethers';
import { EthereumService, ProcessEnvProxy, SubstrateService } from '../..';
import { setOrderPaid } from '@debionetwork/polkadot-provider';
import { ethers } from 'ethers';
import AsyncLock from 'async-lock';

const lock = new AsyncLock();
const ESCROW_WALLET_LOCK_KEY = 'escrow-wallet-lock';

let nonce = 0;
@Injectable()
export class EscrowService {
constructor(
private readonly process: ProcessEnvProxy,
private readonly substrateService: SubstrateService,
private readonly ethereumService: EthereumService,
) {}
private escrowWallet;
private provider;

async onModuleInit(): Promise<void> {
this.provider = await this.ethereumService.getEthersProvider();
this.escrowWallet = await new ethers.Wallet(
this.process.env.DEBIO_ESCROW_PRIVATE_KEY,
this.provider,
);
}

async createOrder(request) {
console.log('[createOrder] request: ', request);
Expand Down Expand Up @@ -43,17 +58,42 @@ export class EscrowService {
}

async orderFulfilled(order): Promise<void> {
try {
const tokenContract = this.ethereumService.getEscrowSmartContract();
const wallet: WalletSigner = await this.ethereumService.createWallet(
this.process.env.DEBIO_ESCROW_PRIVATE_KEY,
);
const tokenContractWithSigner = tokenContract.connect(wallet);
const tx = await tokenContractWithSigner.fulfillOrder(order.id);
console.log('fullfilled order customerId :', order.customerId, ' ->', tx);
} catch (error) {
console.log(error);
}
let currentNonce;
lock
.acquire(ESCROW_WALLET_LOCK_KEY, async () => {
const _nonce = await this.provider.getTransactionCount(
this.escrowWallet.address,
);
nonce = nonce > _nonce ? nonce : _nonce;
const feeData = await this.provider.getFeeData();
const gasPrice = feeData.gasPrice;
const tokenContract = this.ethereumService.getEscrowSmartContract();
const tokenContractWithSigner = tokenContract.connect(
this.escrowWallet,
);
const tx = await tokenContractWithSigner.fulfillOrder(order.id, {
nonce,
gasPrice,
});
currentNonce = nonce;
this.provider.waitForTransaction(tx.hash).then((_tx) => {
console.log(
'fullfilled order customerId :',
order.customerId,
' ->',
_tx,
);
});
nonce += 1;
})
.then(function () {
console.log(
`[fulfillOrder] Sent transaction for nonce: ${currentNonce}`,
);
})
.catch(function (err) {
console.log(err);
});
}

async setOrderPaidWithSubstrate(orderId: string): Promise<void> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,14 +174,8 @@ export class OrderFulfilledHandler
await this.escrowService.orderFulfilled(order);

this.logger.log('OrderFulfilled Event');
this.logger.log('Forwarding payment to lab');
this.logger.log(`labEthAddress: ${labEthAddress}`);
this.logger.log(`amountToForward: ${amountToForward}`);
const tx = await this.escrowService.forwardPaymentToSeller(
labEthAddress,
amountToForward,
);
this.logger.log(`Forward payment transaction sent | tx -> ${tx}`);
} catch (err) {
await this.logger.log(err);
this.logger.log(`Forward payment failed | err -> ${err}`);
Expand Down
13 changes: 2 additions & 11 deletions test/unit/common/modules/escrow/escrow.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,17 +138,8 @@ describe('Escrow Service Unit Tests', () => {
await escrowService.orderFulfilled(ORDER);

// Assert
expect(ethereumServiceMock.getEscrowSmartContract).toHaveBeenCalledTimes(1);
expect(ethereumServiceMock.createWallet).toHaveBeenCalledTimes(1);
expect(ethereumServiceMock.createWallet).toHaveBeenCalledWith(
DEBIO_ESCROW_PRIVATE_KEY,
);
expect(SMART_CONTRACT_MOCK.connect).toHaveBeenCalledTimes(1);
expect(SMART_CONTRACT_MOCK.connect).toHaveBeenCalledWith(WALLET_MOCK);
expect(TOKEN_CONTRACT_SIGNER_MOCK.fulfillOrder).toHaveBeenCalledTimes(1);
expect(TOKEN_CONTRACT_SIGNER_MOCK.fulfillOrder).toHaveBeenCalledWith(
ORDER_ID,
);
expect(ethereumServiceMock.getEscrowSmartContract).not.toBeCalled();
expect(ethereumServiceMock.createWallet).not.toBeCalled();
});

it('should set order paid with substrate', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ describe('Order Fulfilled Handler Event', () => {
expect(convertToDbioUnitStringSpy).toHaveBeenCalledTimes(2);
expect(rewardServiceMock.insert).toHaveBeenCalledTimes(2);
expect(escrowServiceMock.orderFulfilled).toHaveBeenCalled();
expect(escrowServiceMock.forwardPaymentToSeller).toHaveBeenCalled();
expect(escrowServiceMock.forwardPaymentToSeller).not.toHaveBeenCalled();

queryEthAdressByAccountIdSpy.mockClear();
queryOrderDetailByOrderIDSpy.mockClear();
Expand Down Expand Up @@ -605,11 +605,11 @@ describe('Order Fulfilled Handler Event', () => {
transactionLoggingServiceMock.getLoggingByOrderId,
).toHaveBeenCalled();
expect(transactionLoggingServiceMock.create).not.toHaveBeenCalled();
expect(queryEthAdressByAccountIdSpy).not.toHaveBeenCalled();
expect(queryEthAdressByAccountIdSpy).not.toHaveBeenCalledWith(
substrateServiceMock.api,
ORDER.toHuman().sellerId,
);
// expect(queryEthAdressByAccountIdSpy).toHaveBeenCalledTimes(1);
// expect(queryEthAdressByAccountIdSpy).toHaveBeenCalledWith(
// substrateServiceMock.api,
// ORDER.toHuman().sellerId,
// );
expect(queryOrderDetailByOrderIDSpy).not.toHaveBeenCalled();
expect(queryServiceByIdSpy).not.toHaveBeenCalled();
expect(queryServiceInvoiceByOrderIdSpy).not.toHaveBeenCalled();
Expand Down

0 comments on commit 9ab8a23

Please sign in to comment.