Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/pending transactions #221

Merged
merged 2 commits into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions app/controllers/api/v1/community-member/multiSwap/transactions.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
var mongoose = require('mongoose');

module.exports = function (router: any) {

// need to retire this end point
router.post('/create/:txId', asyncMiddleware(async (req: any, res: any) => {

let address = null;
Expand Down Expand Up @@ -240,7 +240,7 @@ module.exports = function (router: any) {
});

}));

// need to retire this end point
router.put('/update/status/:txId', asyncMiddleware(async (req: any, res: any) => {

let address = null;
Expand Down Expand Up @@ -330,4 +330,33 @@ module.exports = function (router: any) {
})
}));

router.post('/do/swap/and/withdraw/:swapTxId', asyncMiddleware(async (req: any, res: any) => {

// validation
swapTransactionHelper.validationForDoSwapAndWithdraw(req);
req.sourceNetwork = await db.Networks.findOne({ _id: req.query.sourceNetworkId });
req.destinationNetwork = await db.Networks.findOne({ _id: req.query.destinationNetworkId });
if(!req.sourceNetwork || !req.destinationNetwork){
throw 'Invalid sourceNetwork or destinationNetwork';
}
// pending swap
let swapAndWithdrawTransaction = await swapTransactionHelper.createPendingSwap(req);

if(swapAndWithdrawTransaction.status == utils.swapAndWithdrawTransactionStatuses.swapPending && !swapAndWithdrawTransaction.nodeJob){
// create job and send api to node
// send call first
swapAndWithdrawTransaction = await swapTransactionHelper.createJobInsideSwapAndWithdraw(req, swapAndWithdrawTransaction);
}

if(swapAndWithdrawTransaction.status == utils.swapAndWithdrawTransactionStatuses.swapCompleted
&& swapAndWithdrawTransaction.nodeJob && swapAndWithdrawTransaction.nodeJob.status == utils.swapAndWithdrawTransactionJobStatuses.completed){
// send getWithdrawSigned call to FIBER Engine backend
swapAndWithdrawTransaction = await withdrawTransactionHelper.doWithdrawSignedFromFIBER(req, swapAndWithdrawTransaction);
}

return res.http200({
swapAndWithdrawTransaction: swapAndWithdrawTransaction
})
}));

};
11 changes: 11 additions & 0 deletions app/controllers/api/v1/transactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,15 @@ module.exports = function (router: any) {
})
}));

router.put('/update/swap/and/withdraw/:swapTxId', asyncMiddleware(async (req: any, res: any) => {

if (!req.params.swapTxId) {
return res.http400('swapTxId is required.');
}
console.log('update swapAndWitdraw body', req.body);
return res.http200({
message: stringHelper.strSuccess
});
}));

};
26 changes: 26 additions & 0 deletions app/lib/httpCalls/fiberHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
var axios = require("axios").default;

module.exports = {

async doWithdrawSigned(req: any, swapAndWithdrawTransactionObject: any, token: any) {
try {
const config = {
headers:{
Authorization: withdrawTransactionHelper.fiberAuthorizationToken()
}
};
let baseUrl = ((global as any) as any).environment.baseUrlFIBEREngineBackend;
let url = `${baseUrl}/multiswap/withdraw/signed?sourceNetworkChainId=${req.sourceNetwork.chainId}&swapTransactionHash=${swapAndWithdrawTransactionObject.receiveTransactionId}`;
console.log('doSwapAndWithdraw doWithdrawSigned url',url);
let res = await axios.get(url, config);
if(res.data.body && res.data.body.data){
console.log('doSwapAndWithdraw doWithdrawSigned hash',res.data.body.data);
return res.data.body.data;
}
} catch (error) {
console.log(error);
}
return null;
}

};
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import Web3 from 'web3';
var { Big } = require("big.js");
let TRANSACTION_TIMEOUT = 36 * 1000;
const abiDecoder = require('abi-decoder'); // NodeJS
var mongoose = require('mongoose');

module.exports = {

Expand Down Expand Up @@ -165,4 +166,70 @@ module.exports = {
return amount;
},

validationForDoSwapAndWithdraw(req: any) {
if (!req.params.swapTxId || !req.query.sourceNetworkId || !req.query.destinationNetworkId
|| !req.query.sourceCabnId || !req.query.destinationCabnId) {
throw 'swapTxId & sourceNetworkId & destinationNetworkId & sourceCabnId & destinationCabnId are required.';
}

if (!mongoose.Types.ObjectId.isValid(req.query.sourceNetworkId)) {
throw 'Invalid sourceNetworkId';
}

if (!mongoose.Types.ObjectId.isValid(req.query.destinationNetworkId)) {
throw 'Invalid destinationNetworkId';
}

if (!mongoose.Types.ObjectId.isValid(req.query.sourceCabnId)) {
throw 'Invalid sourceCabnId';
}

if (!mongoose.Types.ObjectId.isValid(req.query.destinationCabnId)) {
throw 'Invalid destinationCabnId';
}
},

async createPendingSwap(req: any) {
let filter: any = {};
filter.createdByUser = req.user._id;
filter.receiveTransactionId = req.params.swapTxId;
let count = await db.SwapAndWithdrawTransactions.countDocuments(filter)
if(count){
let oldSwapAndWithdrawTransaction = await db.SwapAndWithdrawTransactions.findOne({receiveTransactionId: req.params.txId});
return oldSwapAndWithdrawTransaction;
}

let body: any = {};
body.createdByUser = req.user._id;
body.updatedByUser = req.user._id;
body.createdAt = new Date();
body.updatedAt = new Date();
body.sourceCabn = req.query.sourceCabnId;
body.destinationCabn = req.query.destinationCabnId;
body.sourceNetwork = req.query.sourceNetworkId;
body.destinationNetwork = req.query.destinationNetworkId;
body.status = utils.swapAndWithdrawTransactionStatuses.swapPending;
console.log('doSwapAndWithdraw pendingObject', body);
let swapAndWithdrawTransaction = await db.SwapAndWithdrawTransactions.create(body);
return swapAndWithdrawTransaction;
},

async createJobInsideSwapAndWithdraw(req: any, swapAndWithdrawTransactionObject: any) {
let filter: any = {};
filter._id = swapAndWithdrawTransactionObject._id;

if(!swapAndWithdrawTransactionObject){
throw 'Invalid operation';
}

if(!swapAndWithdrawTransactionObject.nodeJob){
swapAndWithdrawTransactionObject.updatedByUser = req.user._id;
swapAndWithdrawTransactionObject.updatedAt = new Date();
swapAndWithdrawTransactionObject.nodeJob.createdAt = new Date();
swapAndWithdrawTransactionObject.nodeJob.updatedAt = new Date();
swapAndWithdrawTransactionObject = await db.SwapAndWithdrawTransactions.findOneAndUpdate(filter, swapAndWithdrawTransactionObject);
}
return swapAndWithdrawTransactionObject;
},

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import crypto from "crypto";
var CryptoJS = require("crypto-js");
import moment from "moment";

module.exports = {
async doWithdrawSignedFromFIBER(req: any, swapAndWithdrawTransactionObject: any) {

let withdrawHash = await fiberHelper.doWithdrawSigned(req, swapAndWithdrawTransactionObject);
if (withdrawHash) {
console.log('doSwapAndWithdraw withdrawHash', withdrawHash);

}

let filter: any = {};
filter._id = swapAndWithdrawTransactionObject._id;

if (!swapAndWithdrawTransactionObject) {
throw 'Invalid operation';
}

let useTransaction = {
transactionId: withdrawHash,
status: utils.swapAndWithdrawTransactionStatuses.swapWithdrawCompleted,
timestamp: new Date()
}

if (swapAndWithdrawTransactionObject.useTransactions && swapAndWithdrawTransactionObject.useTransactions.length > 0) {
let txItem = (swapAndWithdrawTransactionObject.useTransactions || []).find((t: any) => t.transactionId === req.body.withdrawTxId);
if (!txItem) {
swapAndWithdrawTransactionObject.useTransactions.push(useTransaction);
}
} else {
swapAndWithdrawTransactionObject.useTransactions.push(useTransaction);
}

swapAndWithdrawTransactionObject.updatedByUser = req.user._id;
swapAndWithdrawTransactionObject.updatedAt = new Date();
swapAndWithdrawTransactionObject = await db.SwapAndWithdrawTransactions.findOneAndUpdate(filter, swapAndWithdrawTransactionObject);
return swapAndWithdrawTransactionObject;
},

async fiberAuthorizationToken() {
let timelapse = 5;
let currentTime = new Date();
let startDateTime = moment(currentTime)
.subtract("minutes", timelapse)
.utc()
.format();
let endDateTime = moment(currentTime)
.add("minutes", timelapse)
.utc()
.format();
let randomKey = crypto.randomBytes(512).toString("hex");
let apiKey = process.env.apiKeyForGateway || "";
let tokenBody: any = {};
tokenBody.startDateTime = startDateTime;
tokenBody.endDateTime = endDateTime;
tokenBody.randomKey = randomKey;
tokenBody.apiKey = apiKey;
let strTokenBody = JSON.stringify(tokenBody);
let encryptedSessionToken = CryptoJS.AES.encrypt(strTokenBody, (global as any).environment.jwtSecret).toString();
return 'Bearer ' + encryptedSessionToken;
},
}
20 changes: 18 additions & 2 deletions app/lib/middlewares/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ ecdsaHelper: any,
addressFromPublicKeyHelper: any,
swapUtilsHelper: any,
standardStatuses: any,
smartContractHelper: any
smartContractHelper: any,
withdrawTransactionHelper: any,
fiberHelper: any



Expand Down Expand Up @@ -76,6 +78,20 @@ module.exports = function () {
utils.expectedSchemaVersionV1_0 = '1.0'
utils.expectedSchemaVersionV1_2 = '1.2'
utils.globalTokenExpiryTime = '1800s'

utils.swapAndWithdrawTransactionStatuses = {
swapPending: 'swapPending',
swapCreated: 'swapCreated',
swapCompleted: 'swapCompleted',
swapFailed: 'swapFailed',
swapWithdrawGenerated: 'swapWithdrawGenerated',
swapWithdrawPending: 'swapWithdrawPending',
swapWithdrawFailed: 'swapWithdrawFailed',
swapWithdrawCompleted: 'swapWithdrawCompleted',
}
utils.swapAndWithdrawTransactionJobStatuses = {
pending: 'pending',
failed: 'failed',
completed: 'completed'
}
return utils;
}
5 changes: 5 additions & 0 deletions app/models/swapAndWithdrawTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ var schema = mongoose.Schema({
creator: { type: String, default: "" },
sourceSmartContractAddress: { type: String, default: "" },
destinationSmartContractAddress: { type: String, default: "" },
nodeJob: {
status: { type: String, default: "pending" }, //can be '', 'pending', 'failed', 'completed'
createdAt: { type: Date, default: new Date() },
updatedAt: { type: Date, default: new Date() },
},

},{ collection: 'swapAndWithdrawTransactions' });

Expand Down
2 changes: 2 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,8 @@ if (
(global as any).swapUtilsHelper = require("./app/lib/middlewares/helpers/multiSwapHelpers/swapUtilsHelper");
(global as any).standardStatuses = require("./app/lib/response/standardStatuses");
(global as any).smartContractHelper = require("./app/lib/middlewares/helpers/smartContractHelper");
(global as any).withdrawTransactionHelper = require("./app/lib/middlewares/helpers/multiSwapHelpers/withdrawTransactionHelper");
(global as any).fiberHelper = require("./app/lib/httpCalls/fiberHelper");

(global as any).kraken = app.kraken;
// const whitelist = (global as any).environment.whitelist;
Expand Down