init commit

This commit is contained in:
2025-11-07 22:24:40 +01:00
parent a5373286bf
commit 15b8f36d4d
217 changed files with 168229 additions and 0 deletions

153
server/api/walletApi/bitcoin.js Executable file
View File

@@ -0,0 +1,153 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.bitcoinTransferToExchangeById = exports.bitcoinTransferFromExchange = void 0;
var Client = require('bitcoin-core');
var myError_1 = require("../myError");
var _ = require("lodash");
exports.bitcoinTransferFromExchange = function (value, receiver) { return __awaiter(void 0, void 0, void 0, function () {
var client, query_options;
return __generator(this, function (_a) {
client = new Client({
network: 'testnet',
username: 'polychain',
password: '3QtnxrB7P5y4EpBdad1MkCeB2RHmArvcarw7udgXsAce',
host: "127.0.0.1",
port: 8332
});
query_options = {
"minimumAmount": value,
//"maximumAmount":value,
"maximumCount": 1
};
return [2 /*return*/, client.listUnspent(0, 9999999, [], true, query_options)
.then(function (unspentTx) {
if (unspentTx[0]) {
var txid = unspentTx[0].txid;
var vout = unspentTx[0].vout;
var txValue = unspentTx[0].amount;
var txFee = value * (0.001);
var StxFee = txFee.toFixed(8);
var totalValue = Number(value) + Number(StxFee);
var change = txValue - totalValue;
var Schange = change.toFixed(8);
var nodeAddress = unspentTx[0].address;
var input = [{
"txid": txid,
"vout": vout
}];
var output = [];
var obj = {};
var obj_2 = {};
obj[receiver] = value;
obj_2[nodeAddress] = Schange;
output.push(obj, obj_2);
return client.createRawTransaction(input, output)
.then(function (txHex) {
return client.signRawTransactionWithWallet(txHex)
.then(function (sinedHex) {
return client.sendRawTransaction(sinedHex.hex)
.then(function (txHashOrId) {
return txHashOrId;
})["catch"](function (err) {
console.log("error in sendsigned", err);
throw err;
});
})["catch"](function (err) {
console.log("error in sign ", err);
throw err;
});
})["catch"](function (err) {
console.log("error in create raw tx", err);
throw err;
});
}
else {
var error = new myError_1["default"]('you do not have unspent trancaction', 400, 5, 'تراکنش خرج نشده پیدا نشد', 'خطا رخ داد');
throw error;
}
})["catch"](function (err) {
console.log("error in lisutxo", err);
throw err;
})];
});
}); };
exports.bitcoinTransferToExchangeById = function (txId) { return __awaiter(void 0, void 0, void 0, function () {
var btcAddress, client;
return __generator(this, function (_a) {
btcAddress = ["tb1qfpf6lss60wmle9wanetjxjjt6lc6z65mapk50s"];
client = new Client({
network: 'testnet',
username: 'polychain',
password: '3QtnxrB7P5y4EpBdad1MkCeB2RHmArvcarw7udgXsAce',
host: "127.0.0.1",
port: 8332
});
return [2 /*return*/, client.getTransaction(txId)
.then(function (txInfo) {
if (txInfo) {
var tx = _.find(txInfo.details, function (i) { return i.category.toString() === "receive" && btcAddress.includes(i.address.toString()); });
if (tx) {
var status_1;
if (txInfo.confirmations >= 6) {
status_1 = "Confirmed";
}
else {
status_1 = "pending";
}
var info = {
"txAddress": tx.address,
"txAmount": tx.amount,
"status": status_1
};
return info;
}
else {
var error = new myError_1["default"]('tx not found', 400, 5, 'تراکنش یافت نشد', 'خطا رخ داد');
throw error;
}
}
else {
var error = new myError_1["default"]('transaction not found', 400, 5, 'تراکنش مربوطه پیدا نشد.', 'خطا رخ داد');
throw error;
}
})["catch"](function (err) {
throw err;
})];
});
}); };

132
server/api/walletApi/bitcoin.ts Executable file
View File

@@ -0,0 +1,132 @@
const Client = require('bitcoin-core')
import myError from '../myError'
import * as _ from 'lodash'
export const bitcoinTransferFromExchange = async(value, receiver) => {
const client = new Client({
network: 'testnet',
username: 'polychain',
password: '3QtnxrB7P5y4EpBdad1MkCeB2RHmArvcarw7udgXsAce',
host:"127.0.0.1",
port:8332
})
const query_options = {
"minimumAmount":value,
//"maximumAmount":value,
"maximumCount":1 ,
}
return client.listUnspent(0, 9999999, [], true, query_options)
.then((unspentTx) => {
if(unspentTx[0]) {
const txid = unspentTx[0].txid
const vout = unspentTx[0].vout
const txValue = unspentTx[0].amount
let txFee = value*(0.001)
const StxFee = txFee.toFixed(8)
const totalValue = Number(value) + Number(StxFee)
let change = txValue - totalValue
const Schange = change.toFixed(8)
const nodeAddress = unspentTx[0].address
const input = [{
"txid": txid,
"vout": vout,
}]
let output = []
let obj = {}
let obj_2 ={}
obj[receiver] = value
obj_2[nodeAddress] = Schange
output.push(obj,obj_2)
return client.createRawTransaction(input,output)
.then((txHex) => {
return client.signRawTransactionWithWallet(txHex)
.then((sinedHex) => {
return client.sendRawTransaction(sinedHex.hex)
.then((txHashOrId) => {
return txHashOrId
})
.catch((err) => {
console.log("error in sendsigned",err)
throw err
})
})
.catch((err)=>{
console.log("error in sign ",err)
throw err
})
})
.catch((err )=> {
console.log("error in create raw tx",err)
throw err
})
} else {
const error = new myError(
'you do not have unspent trancaction',
400,
5,
'تراکنش خرج نشده پیدا نشد',
'خطا رخ داد'
)
throw error
}
})
.catch((err) => {
console.log("error in lisutxo",err)
throw err
})
}
export const bitcoinTransferToExchangeById = async(txId) => {
const btcAddress = ["tb1qfpf6lss60wmle9wanetjxjjt6lc6z65mapk50s"]
const client = new Client({
network: 'testnet',
username: 'polychain',
password: '3QtnxrB7P5y4EpBdad1MkCeB2RHmArvcarw7udgXsAce',
host: "127.0.0.1",
port: 8332
})
return client.getTransaction(txId)
.then((txInfo) => {
if(txInfo){
const tx = _.find(txInfo.details, (i) => { return i.category.toString() === "receive" && btcAddress.includes(i.address.toString())})
if(tx) {
let status
if(txInfo.confirmations>=6)
{
status = "Confirmed"
}else{
status = "pending"
}
const info = {
"txAddress":tx.address,
"txAmount":tx.amount,
"status":status
}
return info
} else {
const error = new myError(
'tx not found',
400,
5,
'تراکنش یافت نشد',
'خطا رخ داد'
)
throw error
}
} else {
const error = new myError(
'transaction not found',
400,
5,
'تراکنش مربوطه پیدا نشد.',
'خطا رخ داد'
)
throw error
}
})
.catch((err) => {
throw err
})
}

201
server/api/walletApi/etheriuem.js Executable file
View File

@@ -0,0 +1,201 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.getAccounts = exports.receiveEtherFromClient = exports.sendEther = exports.getEtheriumNonce = exports.checkTransaction = exports.getBalance = exports.createPersonalAccount = exports.createAccount = void 0;
var ethereumjs_common_1 = require("ethereumjs-common");
var Web3 = require('web3');
var Tx = require('ethereumjs-tx').Transaction;
exports.createAccount = function () {
var web3 = new Web3("http://localhost:8545");
var data = web3.eth.accounts.create();
return data;
};
exports.createPersonalAccount = function () {
var web3 = new Web3("http://localhost:8545");
return web3.eth.personal.newAccount("exchange")
.then(function (result) {
return result;
})["catch"](function (err) {
console.log(err);
});
};
exports.getBalance = function (account) { return __awaiter(void 0, void 0, void 0, function () {
var web3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Web3("http://localhost:8545")];
case 1:
web3 = _a.sent();
return [2 /*return*/, web3.eth.getBalance(account.toString())
.then(function (balance) {
return balance;
})["catch"](function (err) {
throw err;
})];
}
});
}); };
exports.checkTransaction = function (transactionId) { return __awaiter(void 0, void 0, void 0, function () {
var web3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Web3("http://localhost:8545")];
case 1:
web3 = _a.sent();
return [2 /*return*/, web3.eth.getTransactionReceipt(transactionId)
.then(function (txR) {
if (txR.blockNumber == undefined) {
throw "transaction receipt not found";
}
else {
return web3.eth.getTransaction(transactionId)
.then(function (tx) {
if (tx.blockNumber == undefined || tx.value == undefined) {
throw "transaction receipt not found";
}
else {
return tx;
}
})["catch"](function (err) {
throw err;
});
}
})["catch"](function (err) {
throw (err);
})];
}
});
}); };
exports.getEtheriumNonce = (function (address) {
var web3 = new Web3("http://localhost:8545");
return web3.eth.getTransactionCount(address, 'pending')
.then(function (nonce) {
//got nonce proceed with creating and signing transaction
return nonce;
})["catch"](function (err) {
throw err;
});
});
exports.sendEther = function (account, value) { return __awaiter(void 0, void 0, void 0, function () {
var web3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Web3("http://localhost:8545")];
case 1:
web3 = _a.sent();
//unlock it for a period of 15 secs
return [2 /*return*/, web3.eth.personal.unlockAccount("0x868453967f6806ef86de7cf5e57a32ab28b875b4", "exchange", 15000)
.then(function (unlocked) {
return web3.eth.sendTransaction({
//from: process.env.ADMIN_ETHERIUM_ACCOUNT_ADDRESS,
from: '0x868453967f6806ef86de7cf5e57a32ab28b875b4',
to: account.toString(),
value: web3.utils.toWei(value.toString())
})
.then(function (receipt) {
// then lock it
return web3.eth.personal.lockAccount("0x868453967f6806ef86de7cf5e57a32ab28b875b4")
.then(function () {
return receipt;
})["catch"](function (err) {
return receipt;
});
})["catch"](function (err) {
throw err;
});
})["catch"](function (err) {
throw (err);
})];
}
});
}); };
exports.receiveEtherFromClient = function (transactionHash) {
//receive transaction from the ui and send it
var web3 = new Web3("http://localhost:8545");
var rawTx = undefined;
var transaction = undefined;
//custom network
var customCommon = ethereumjs_common_1["default"].forCustomChain('mainnet', {
name: 'my-network',
networkId: 1981,
chainId: 1981
}, 'petersburg');
var preData = function () {
var privateKey = Buffer.from('64061456066baa81c5097c895b5176fb3e1452eaf6f6776e2d7bf07ddb9accfe', 'hex');
//parameters should be hex string starting with 0x
var txParams = {
nonce: '0x01',
gas: 50002,
gasPrice: Number(web3.utils.toWei('601', 'gwei')),
to: '0x868453967f6806ef86de7cf5e57a32ab28b875b4',
value: 10000003
};
// The second parameter is not necessary if these values are used
var tx = new Tx(txParams, { common: customCommon });
tx.sign(privateKey);
var serializedTx = tx.serialize();
return rawTx = '0x' + serializedTx.toString('hex');
};
return Promise.all([preData()])
.then(function () {
return web3.eth.sendSignedTransaction(rawTx)
.then(function (result) {
return result;
})["catch"](function (err) {
throw err;
});
})["catch"](function (err) {
throw err;
});
};
exports.getAccounts = function () { return __awaiter(void 0, void 0, void 0, function () {
var web3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, new Web3("http://localhost:8545")];
case 1:
web3 = _a.sent();
return [2 /*return*/, web3.eth.getAccounts()
.then(function (result) {
console.log("all acounts is ", result);
})["catch"](function (err) {
throw err;
})];
}
});
}); };

157
server/api/walletApi/etheriuem.ts Executable file
View File

@@ -0,0 +1,157 @@
import Common from 'ethereumjs-common'
const Web3 = require('web3');
const Tx = require('ethereumjs-tx').Transaction;
export const createAccount = () => {
const web3 = new Web3( "http://localhost:8545");
const data = web3.eth.accounts.create()
return data
}
export const createPersonalAccount = () => {
const web3 = new Web3( "http://localhost:8545");
return web3.eth.personal.newAccount("exchange")
.then((result) => {
return result
})
.catch((err) => {
console.log(err)
})
}
export const getBalance = async (account) => {
const web3 = await new Web3( "http://localhost:8545");
return web3.eth.getBalance(account.toString())
.then((balance) => {
return balance
})
.catch((err) => {
throw err
})
}
export const checkTransaction = async (transactionId) => {
const web3 = await new Web3( "http://localhost:8545");
return web3.eth.getTransactionReceipt(transactionId)
.then((txR) => {
if (txR.blockNumber == undefined) {
throw "transaction receipt not found";
} else {
return web3.eth.getTransaction(transactionId)
.then((tx) => {
if (tx.blockNumber == undefined|| tx.value == undefined) {
throw "transaction receipt not found";
} else {
return tx
}
})
.catch((err) => {
throw err
})
}
}).catch((err)=>{
throw(err)
})
}
export const getEtheriumNonce=((address) => {
const web3 = new Web3( "http://localhost:8545");
return web3.eth.getTransactionCount(address,'pending')
.then((nonce) => {
//got nonce proceed with creating and signing transaction
return nonce;
})
.catch((err) => {
throw err
})
})
export const sendEther = async (account,value) => {
const web3 = await new Web3( "http://localhost:8545");
//unlock it for a period of 15 secs
return web3.eth.personal.unlockAccount("0x868453967f6806ef86de7cf5e57a32ab28b875b4","exchange", 15000)
.then((unlocked) => {
return web3.eth.sendTransaction({
//from: process.env.ADMIN_ETHERIUM_ACCOUNT_ADDRESS,
from: '0x868453967f6806ef86de7cf5e57a32ab28b875b4',
to: account.toString(),
value: web3.utils.toWei (value.toString())
})
.then((receipt) => {
// then lock it
return web3.eth.personal.lockAccount("0x868453967f6806ef86de7cf5e57a32ab28b875b4")
.then(() => {
return receipt
})
.catch((err) => {
return receipt
})
})
.catch((err) =>{
throw err
})
}).catch((err)=>{
throw(err)
})
}
export const receiveEtherFromClient = (transactionHash) => {
//receive transaction from the ui and send it
const web3 = new Web3( "http://localhost:8545");
let rawTx = undefined
let transaction = undefined
//custom network
const customCommon = Common.forCustomChain(
'mainnet',
{
name: 'my-network',
networkId: 1981,
chainId: 1981,
},
'petersburg',
)
const preData = () => {
const privateKey = Buffer.from(
'64061456066baa81c5097c895b5176fb3e1452eaf6f6776e2d7bf07ddb9accfe',
'hex'
)
//parameters should be hex string starting with 0x
const txParams = {
nonce: '0x01',
gas: 50002,
gasPrice: Number(web3.utils.toWei('601', 'gwei')),
to: '0x868453967f6806ef86de7cf5e57a32ab28b875b4',
value: 10000003
}
// The second parameter is not necessary if these values are used
const tx = new Tx(txParams,{common : customCommon})
tx.sign(privateKey)
const serializedTx = tx.serialize()
return rawTx = '0x' + serializedTx.toString('hex');
}
return Promise.all([preData()])
.then(()=>{
return web3.eth.sendSignedTransaction(rawTx)
.then((result) => {
return result;
})
.catch((err) => {
throw err;
})
})
.catch((err) => {
throw err
})
}
export const getAccounts = async () => {
const web3 = await new Web3( "http://localhost:8545");
return web3.eth.getAccounts()
.then((result)=>{
console.log("all acounts is ", result)
})
.catch((err)=>{
throw err
})
}

View File

@@ -0,0 +1,220 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.transferFromExchangeApi = void 0;
var myError_1 = require("../myError");
var currencies_1 = require("../../db/currencies");
var bitcoin = require("../walletApi/bitcoin");
var etheriuem = require("../walletApi/etheriuem");
var mongoose = require("mongoose");
var user_1 = require("../../db/user");
var _ = require("lodash");
var pendingTransfers_1 = require("../../db/pendingTransfers");
exports.transferFromExchangeApi = function (currencyId, value, receiver, userId) { return __awaiter(void 0, void 0, void 0, function () {
var info, resObj, checkStatus, session;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
checkStatus = function () {
return null;
};
return [4 /*yield*/, mongoose.startSession()];
case 1:
session = _a.sent();
return [2 /*return*/, session.withTransaction(function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2 /*return*/, user_1.User.findOne({ _id: userId }).session(session)
.then(function (user) { return __awaiter(void 0, void 0, void 0, function () {
var error;
return __generator(this, function (_a) {
if (user) {
return [2 /*return*/, currencies_1.Currencies.findOne({ _id: currencyId })
.then(function (cur) { return __awaiter(void 0, void 0, void 0, function () {
var CurAbName, curInWall_1, error, error, error;
return __generator(this, function (_a) {
CurAbName = "";
if (cur) {
curInWall_1 = _.find(user.wallet, function (i) { return i.currency.toString() === currencyId.toString(); });
if (curInWall_1) {
if (curInWall_1.value >= Number(value)) {
CurAbName = cur.ab_name;
switch (CurAbName) {
case "BTC":
checkStatus = function () {
return bitcoin.bitcoinTransferFromExchange(value, receiver)
.then(function (txHash) {
info = {
status: "pending",
txHash: txHash
};
})["catch"](function (err) {
throw err;
});
};
case "ETH":
return [2 /*return*/, etheriuem.sendEther(receiver.toString(), value)
.then(function (result) { return __awaiter(void 0, void 0, void 0, function () {
var bodySuccessfulOffer, bodyTransaction;
return __generator(this, function (_a) {
if (result && result.transactionHash) {
bodySuccessfulOffer = {
userId: user._id,
transactions: []
};
bodyTransaction = {
txId: result.transactionHash,
currencyId: currencyId,
currencyName: CurAbName,
value: Number(value),
type: 'send'
};
bodySuccessfulOffer.transactions.push(bodyTransaction);
}
else if (result) {
throw ("could not get any transaction " + result);
}
else {
throw ("could not get result ");
}
return [2 /*return*/];
});
}); })["catch"](function (err) {
throw err;
})];
case "TRX":
}
return [2 /*return*/, Promise.all([checkStatus()])
.then(function () {
return pendingTransfers_1.PendingTransfers.findOne({ userId: userId }).session(session)
.then(function (userPending) { return __awaiter(void 0, void 0, void 0, function () {
var usrPending;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!userPending) return [3 /*break*/, 2];
userPending.transactions.push({
txId: info.txHash,
currencyId: currencyId,
currencyName: CurAbName,
value: value,
type: "send"
});
return [4 /*yield*/, userPending.save()];
case 1:
_a.sent();
return [3 /*break*/, 4];
case 2:
usrPending = {
userId: userId,
transactions: [{
txId: info.txHash,
currencyId: currencyId,
currencyName: CurAbName,
value: value,
type: "id"
}]
};
return [4 /*yield*/, pendingTransfers_1.PendingTransfers.create([usrPending], { session: session })];
case 3:
_a.sent();
_a.label = 4;
case 4:
curInWall_1.value -= value;
return [4 /*yield*/, user.save()];
case 5:
_a.sent();
resObj =
{
status: "success",
txValue: value,
txHash: info.txHash
};
return [2 /*return*/];
}
});
}); })["catch"](function (err) {
throw err;
});
})["catch"](function (err) {
throw err;
})];
}
else {
error = new myError_1["default"]('you do not have enough currency ', 400, 5, 'موجودی کافی نمی باشد', 'خطا رخ داد');
throw error;
}
}
else {
error = new myError_1["default"]('currency not found in user wallet', 400, 5, 'ارز در کیف پول پیدا نشد', 'خطا رخ داد');
throw error;
}
}
else {
error = new myError_1["default"]('currency not found', 400, 5, 'ارز پیدا نشد', 'خطا رخ داد');
throw error;
}
return [2 /*return*/];
});
}); })["catch"](function (err) {
throw err;
})];
}
else {
error = new myError_1["default"]('user not found', 400, 5, 'کاربر پیدا نشد.', 'خطا رخ داد');
throw error;
}
return [2 /*return*/];
});
}); })["catch"](function (err) {
throw err;
})];
});
}); })
.then(function () {
return resObj;
})["catch"](function (err) {
console.log("error in with Transaction", err);
throw ("error in with transaction");
})["finally"](function () {
session.endSession();
})["catch"](function (err) {
throw err;
})];
}
});
}); };

View File

@@ -0,0 +1,189 @@
import myError from '../myError'
import { Currencies } from '../../db/currencies'
import * as bitcoin from '../walletApi/bitcoin'
import * as etheriuem from '../walletApi/etheriuem'
import * as tron from '../walletApi/tron'
import * as mongoose from 'mongoose'
import { User } from '../../db/user'
import * as _ from 'lodash'
import { PendingTransfers } from '../../db/pendingTransfers'
import { SuccessfulTransfers } from '../../db/successfulTransfers'
export const transferFromExchangeApi = async(currencyId, value, receiver, userId) => {
let info
let resObj
let checkStatus = () => {
return null
}
const session = await mongoose.startSession()
return session.withTransaction(async() => {
return User.findOne({_id:userId}).session(session)
.then(async (user)=>{
if(user){
return Currencies.findOne({_id:currencyId})
.then(async(cur) => {
let CurAbName = ""
if(cur){
let curInWall = _.find(user.wallet, (i) => { return i.currency.toString() === currencyId.toString()})
if(curInWall) {
if(curInWall.value >= Number(value)){
CurAbName = cur.ab_name
switch(CurAbName) {
case "BTC":
checkStatus = () => {
return bitcoin.bitcoinTransferFromExchange(value,receiver)
.then((txHash) => {
info = {
status:"pending",
txHash:txHash
}
})
.catch((err)=>{
throw err
})
}
case "ETH":
return etheriuem.sendEther(receiver.toString(),value)
.then(async (result) => {
if(result&&result.transactionHash) {
const bodySuccessfulOffer = {
userId: user._id ,
transactions : []
}
const bodyTransaction = {
txId : result.transactionHash,
currencyId : currencyId,
currencyName : CurAbName,
value : Number(value),
type : 'send'
}
bodySuccessfulOffer.transactions.push(bodyTransaction)
} else if(result) {
throw ("could not get any transaction "+ result)
} else {
throw ("could not get result ")
}
})
.catch((err) => {
throw err
})
case "TRX":
}
return Promise.all([checkStatus()])
.then(() =>{
return PendingTransfers.findOne({ userId:userId }).session(session)
.then(async (userPending) => {
if(userPending){
userPending.transactions.push({
txId: info.txHash,
currencyId: currencyId,
currencyName: CurAbName,
value: value,
type: "send"
})
await userPending.save()
} else {
const usrPending = {
userId: userId,
transactions: [{
txId: info.txHash,
currencyId: currencyId,
currencyName: CurAbName,
value: value,
type: "id"
}]
}
await PendingTransfers.create([usrPending],{ session })
}
curInWall.value -= value
await user.save()
resObj =
{
status:"success",
txValue:value,
txHash:info.txHash
}
}).catch((err)=>{
throw err
})
}).catch((err)=>{
throw err
})
} else {
const error = new myError(
'you do not have enough currency ',
400,
5,
'موجودی کافی نمی باشد',
'خطا رخ داد'
)
throw error
}
} else {
const error = new myError(
'currency not found in user wallet',
400,
5,
'ارز در کیف پول پیدا نشد',
'خطا رخ داد'
)
throw error
}
} else {
const error = new myError(
'currency not found',
400,
5,
'ارز پیدا نشد',
'خطا رخ داد'
)
throw error
}
}).catch((err)=>{
throw err
})
} else {
const error = new myError(
'user not found',
400,
5,
'کاربر پیدا نشد.',
'خطا رخ داد'
)
throw error
}
}).catch((err)=>{
throw err
})
})
.then(() => {
return resObj
})
.catch((err) => {
console.log("error in with Transaction",err)
throw("error in with transaction")
})
.finally(() => {
session.endSession()
})
.catch((err) => {
throw err
})
}

View File

@@ -0,0 +1,128 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.transferInWithTxId = void 0;
var Client = require('bitcoin-core');
var _ = require("lodash");
exports.transferInWithTxId = function (currency, txId) { return __awaiter(void 0, void 0, void 0, function () {
var client_1;
return __generator(this, function (_a) {
switch (currency) {
case "BTC":
client_1 = new Client({
network: 'testnet',
username: 'polychain',
password: '3QtnxrB7P5y4EpBdad1MkCeB2RHmArvcarw7udgXsAce',
host: "127.0.0.1",
port: 8332
});
client_1.listTransactions("*", 100, 0)
.theb(function (txs) {
var tx = _.find(txs, function (i) { return i.txid.toString() === txId.toString(); });
if (tx) {
if (tx.address === "node address") {
var amount_1 = tx.amount;
client_1.getBlockCount()
.then(function (blockCount) {
if (blockCount - Number(tx.blockindex) > 6) {
return amount_1;
}
else {
//
}
})["catch"](function (err) {
throw err;
});
}
else {
}
}
})["catch"](function (err) {
throw err;
});
break;
case "ETH":
//
break;
case "TRX":
//
break;
}
return [2 /*return*/];
});
}); };
// fetch("connect to your bitcoin node",{
// method: "POST",
// body:{"jsonrpc": "1.0", "id":"curltest",
// "method": "listtransactions",
// "params": [txId]
// },
// headers:header
// })
// .then(res => res.json())
// .then((txs) => {
// const tx = _.find(txs, (i) => { return i.txid.toString()=== txId.toString()})
// if(tx){
// const blockIndex = Number(tx.blockindex)
// const txValue = Number(tx.vout)
// fetch("connect to your bitcoin node",{
// method: "POST",
// body:{"jsonrpc": "1.0", "id":"curltest",
// "method": "getblockcount",
// "params": []
// },
// headers:header
// })
// .then(res => res.json())
// .then((blockCount) => {
// if(Number(blockCount)-blockIndex>=6) {
// let cur = _.find(user.wallet, (i) => { return i.currency.toString()=== currencyId.toString() })
// cur.value += txValue
// } else {
// //wait for transaction confirmation
// }
// }).catch((err)=>{
// next(err)
// })
// } else {
// //throw errrrrorrrrrr
// }
// })
// .catch((err) => {
// next(err)
// })

View File

@@ -0,0 +1,114 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.transferToApi = void 0;
var Client = require('bitcoin-core');
exports.transferToApi = function (currency, value, receiver) { return __awaiter(void 0, void 0, void 0, function () {
var client_1, query_options;
return __generator(this, function (_a) {
switch (currency) {
case "BTC":
client_1 = new Client({
network: 'testnet',
username: 'polychain',
password: '3QtnxrB7P5y4EpBdad1MkCeB2RHmArvcarw7udgXsAce',
host: "127.0.0.1",
port: 8332
});
query_options = {
"minimumAmount": value
};
client_1.listUnspent(1, 1, [], true, query_options)
.then(function (unspentTx) {
if (unspentTx[0]) {
var txid = unspentTx[0].txid;
var txValue = Number(unspentTx[0].amount);
var change = txValue - value;
var nodeAddress_1 = unspentTx[0].address;
var input = [{
"txid": txid,
"vout": Number(txValue)
}];
var output = [
{
"receiver": txValue,
"nodeAddress": change
},
{
"data": "Hi"
},
];
client_1.createRawTransaction(input, output)
.then(function (txHex) {
client_1.dumpprivkey(nodeAddress_1)
.then(function (priKey) {
client_1.signRawTransactionWithKey(txHex, [priKey])
.then(function (sinedHex) {
client_1.sendRawTransaction(sinedHex)
.then(function (txHashOrId) {
return txHashOrId;
})["catch"](function (err) {
throw (err);
});
})["catch"](function (err) {
throw (err);
});
})["catch"](function (err) {
throw (err);
});
})["catch"](function (err) {
throw (err);
});
}
else {
// throw err
}
})["catch"](function (err) {
console.log('the error is', err);
});
break;
case "ETH":
//
break;
case "TRX":
//
break;
}
return [2 /*return*/];
});
}); };

View File

@@ -0,0 +1,100 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.transferToExchangeApi = void 0;
var Client = require('bitcoin-core');
var myError_1 = require("../myError");
var currencies_1 = require("../../db/currencies");
exports.transferToExchangeApi = function (currencyId, signedRawTxHex, value) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
currencies_1.Currencies.findOne({ _id: currencyId })
.then(function (cur) {
var CurAbName = "";
if (cur) {
value = Number(value);
CurAbName = cur.ab_name;
switch (CurAbName) {
case "BTC":
// const client = new Client({
// network: 'testnet',
// username: 'polychain',
// password: '3QtnxrB7P5y4EpBdad1MkCeB2RHmArvcarw7udgXsAce',
// host:"127.0.0.1",
// port:8332
// })
// client.decodeRawTransaction(signedRawTxHex)
// .then((tx) => {
// if(tx) {
// const txValue = Number(tx[0].vout[0].value)
// if(txValue===Number(value)) {
// client.sendRawTransaction(signedRawTxHex)
// .then((txHashOrId) => {
// return txHashOrId
// })
// .catch((err) => {
// throw(err)
// })
// } else {
// //
// }
// } else {
// //
// }
// })
// .catch((err) => {
// throw err
// })
break;
case "ETH":
//
break;
case "TRX":
//
break;
}
}
else {
var error = new myError_1["default"]('currency not found', 400, 5, 'ارز مربوطه پیدا نشد.', 'خطا رخ داد');
throw error;
}
})["catch"](function (err) {
throw err;
});
return [2 /*return*/];
});
}); };

View File

@@ -0,0 +1,70 @@
const Client = require('bitcoin-core')
import { conformsTo } from 'lodash'
import myError from '../myError'
import { Currencies } from '../../db/currencies'
export const transferToExchangeApi = async(currencyId,signedRawTxHex,value) => {
Currencies.findOne({_id:currencyId})
.then((cur)=>{
let CurAbName = ""
if(cur){
value = Number(value)
CurAbName = cur.ab_name
switch(CurAbName) {
case "BTC":
// const client = new Client({
// network: 'testnet',
// username: 'polychain',
// password: '3QtnxrB7P5y4EpBdad1MkCeB2RHmArvcarw7udgXsAce',
// host:"127.0.0.1",
// port:8332
// })
// client.decodeRawTransaction(signedRawTxHex)
// .then((tx) => {
// if(tx) {
// const txValue = Number(tx[0].vout[0].value)
// if(txValue===Number(value)) {
// client.sendRawTransaction(signedRawTxHex)
// .then((txHashOrId) => {
// return txHashOrId
// })
// .catch((err) => {
// throw(err)
// })
// } else {
// //
// }
// } else {
// //
// }
// })
// .catch((err) => {
// throw err
// })
break;
case "ETH":
//
break;
case "TRX":
//
break;
}
}else{
const error = new myError(
'currency not found',
400,
5,
'ارز مربوطه پیدا نشد.',
'خطا رخ داد'
)
throw error
}
}).catch((err)=>{
throw err
})
}

View File

@@ -0,0 +1,363 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.transferToExchangeByIdApi = void 0;
var _ = require("lodash");
var myError_1 = require("../myError");
var currencies_1 = require("../../db/currencies");
var user_1 = require("../../db/user");
var mongoose = require("mongoose");
var bitcoin = require("../walletApi/bitcoin");
var etherium = require("./etheriuem");
var tron = require("./tron");
var pendingTransfers_1 = require("../../db/pendingTransfers");
var successfulTransfers_1 = require("../../db/successfulTransfers");
exports.transferToExchangeByIdApi = function (currencyId, txId, userId) { return __awaiter(void 0, void 0, void 0, function () {
var info, resObj, userHaveDoc, checkStatus, session;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
userHaveDoc = false;
checkStatus = function () {
return null;
};
return [4 /*yield*/, mongoose.startSession()];
case 1:
session = _a.sent();
return [2 /*return*/, session.withTransaction(function () {
return user_1.User.findOne({ _id: userId }).session(session)
.then(function (user) {
if (user) {
return pendingTransfers_1.PendingTransfers.findOne({ userId: userId })
.then(function (userPending) {
if (userPending && userPending.userId.toString() === userId.toString()) {
userHaveDoc = true;
var pendingTx = _.find(userPending.transactions, function (i) { return i.txId.toString() === txId.toString(); });
if (pendingTx) {
var error = new myError_1["default"]('transaction already exsist', 400, 5, 'تراکنش قبلا وجود دارد', 'خطا رخ داد');
throw error;
}
}
return currencies_1.Currencies.findOne({ _id: currencyId })
.then(function (cur) {
var CurAbName = "";
if (cur) {
CurAbName = cur.ab_name;
switch (CurAbName) {
case "BTC":
checkStatus = function () {
return bitcoin.bitcoinTransferToExchangeById(txId)
.then(function (result) {
info = result;
})["catch"](function (err) {
throw err;
});
};
break;
case "ETH":
return etherium.checkTransaction(txId)
.then(function (transaction) {
if (transaction && transaction.hash.toString() === txId.toString()) {
var curInWall = _.find(user.wallet, function (i) { return i.currency.toString() === currencyId.toString(); });
if (curInWall) {
curInWall.value += Number(transaction.value);
}
else {
}
return;
}
else {
throw "transaction not valid";
}
})["catch"](function (err) {
console.log("api error: ", err);
});
//
case "TRX":
return tron.validateByTXId(txId)
.then(function (transaction) {
if (transaction.result) {
var resObj_1 = {
status: "successful",
txValue: transaction
};
return resObj_1;
}
else {
var resObj_2 = {
status: "pending",
txValue: transaction
};
}
})["catch"](function (err) {
throw (err);
});
// default
}
return Promise.all([checkStatus()])
.then(function () {
if (userHaveDoc) {
userPending.transactions.push({
txId: txId,
currencyId: currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
});
userPending.save()
.then(function () {
if (info.status === 'Confirmed') {
return successfulTransfers_1.SuccessfulTransfers.findOne({ userId: userId }).session(session)
.then(function (userSuccess) { return __awaiter(void 0, void 0, void 0, function () {
var usrSuccess;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(userSuccess && userSuccess.userId.toString() === userId.toString())) return [3 /*break*/, 2];
userSuccess.transactions.push({
txId: txId,
currencyId: currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
});
return [4 /*yield*/, userSuccess.save()];
case 1:
_a.sent();
return [3 /*break*/, 4];
case 2:
usrSuccess = {
userId: userId,
transactions: [{
txId: txId,
currencyId: currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
}]
};
return [4 /*yield*/, successfulTransfers_1.SuccessfulTransfers.create([usrSuccess], { session: session })];
case 3:
_a.sent();
_a.label = 4;
case 4: return [2 /*return*/, pendingTransfers_1.PendingTransfers.findOne({ userId: userId }).session(session)
.then(function (userPendinAfterSave) { return __awaiter(void 0, void 0, void 0, function () {
var cur;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
userPendinAfterSave.transactions = _.filter(userPendinAfterSave.transactions, function (i) { return i.txId.toString() !== txId.toString(); });
return [4 /*yield*/, userPendinAfterSave.save()];
case 1:
_a.sent();
cur = _.find(user.wallet, function (i) { return i.currency.toString() === currencyId.toString(); });
if (!cur) return [3 /*break*/, 3];
cur.value += info.txAmount;
return [4 /*yield*/, user.save()];
case 2:
_a.sent();
return [3 /*break*/, 5];
case 3:
user.wallet.push({
currency: currencyId,
value: info.txAmount
});
return [4 /*yield*/, user.save()];
case 4:
_a.sent();
_a.label = 5;
case 5:
resObj = {
status: 'successful',
value: info.txAmount
};
return [2 /*return*/];
}
});
}); })["catch"](function (err) {
throw err;
})];
}
});
}); })["catch"](function (err) {
throw err;
});
}
else {
resObj = {
status: 'pending',
value: info.txAmount
};
}
})["catch"](function (err) {
throw err;
});
}
else {
var usrPending = {
userId: userId,
transactions: [{
txId: txId,
currencyId: currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
}]
};
pendingTransfers_1.PendingTransfers.create([usrPending])
.then(function () {
if (info.status === 'Confirmed') {
return successfulTransfers_1.SuccessfulTransfers.findOne({ userId: userId }).session(session)
.then(function (userSuccess) { return __awaiter(void 0, void 0, void 0, function () {
var usrSuccess;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(userSuccess && userSuccess.userId.toString() === userId.toString())) return [3 /*break*/, 2];
userSuccess.transactions.push({
txId: txId,
currencyId: currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
});
return [4 /*yield*/, userSuccess.save()];
case 1:
_a.sent();
return [3 /*break*/, 4];
case 2:
usrSuccess = {
userId: userId,
transactions: [{
txId: txId,
currencyId: currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
}]
};
return [4 /*yield*/, successfulTransfers_1.SuccessfulTransfers.create([usrSuccess], { session: session })];
case 3:
_a.sent();
_a.label = 4;
case 4: return [2 /*return*/, pendingTransfers_1.PendingTransfers.findOne({ userId: userId }).session(session)
.then(function (userPendinAfterSave) { return __awaiter(void 0, void 0, void 0, function () {
var cur;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
userPendinAfterSave.transactions = _.filter(userPendinAfterSave.transactions, function (i) { return i.txId.toString() !== txId.toString(); });
return [4 /*yield*/, userPendinAfterSave.save()];
case 1:
_a.sent();
cur = _.find(user.wallet, function (i) { return i.currency.toString() === currencyId.toString(); });
if (!cur) return [3 /*break*/, 3];
cur.value += info.txAmount;
return [4 /*yield*/, user.save()];
case 2:
_a.sent();
return [3 /*break*/, 5];
case 3:
user.wallet.push({
currency: currencyId,
value: info.txAmount
});
return [4 /*yield*/, user.save()];
case 4:
_a.sent();
_a.label = 5;
case 5:
resObj = {
status: 'successful',
value: info.txAmount
};
return [2 /*return*/];
}
});
}); })["catch"](function (err) {
throw err;
})];
}
});
}); })["catch"](function (err) {
throw err;
});
}
else {
resObj = {
status: 'pending',
value: info.txAmount
};
}
})["catch"](function (err) {
throw err;
});
}
})["catch"](function (err) {
throw err;
});
}
else {
var error = new myError_1["default"]('currency not found', 400, 5, 'ارز مربوطه پیدا نشد.', 'خطا رخ داد');
throw error;
}
})["catch"](function (err) {
throw err;
});
})["catch"](function (err) {
throw err;
});
}
else {
var error = new myError_1["default"]('user not found', 400, 5, 'کاربر پیدا نشد.', 'خطا رخ داد');
throw error;
}
})["catch"](function (err) {
throw err;
});
})
.then(function () {
return resObj;
})["catch"](function (err) {
throw ("error in with Transaction" + ":" + err);
})["finally"](function () {
session.endSession();
})];
}
});
}); };

View File

@@ -0,0 +1,291 @@
import * as _ from 'lodash'
import myError from '../myError'
import { Currencies } from '../../db/currencies'
import { User } from '../../db/user'
import * as mongoose from 'mongoose'
import * as bitcoin from '../walletApi/bitcoin'
import * as etherium from './etheriuem'
import * as tron from './tron'
import { PendingTransfers } from '../../db/pendingTransfers'
import { SuccessfulTransfers } from '../../db/successfulTransfers'
export const transferToExchangeByIdApi = async(currencyId, txId, userId) => {
let info
let resObj
let userHaveDoc = false
let checkStatus = () => {
return null
}
const session = await mongoose.startSession()
return session.withTransaction(() => {
return User.findOne({ _id: userId }).session(session)
.then((user) => {
if(user) {
return PendingTransfers.findOne({ userId: userId })
.then((userPending) => {
if(userPending && userPending.userId.toString() === userId.toString()) {
userHaveDoc = true
let pendingTx = _.find(userPending.transactions, (i) => { return i.txId.toString() === txId.toString() })
if(pendingTx) {
const error = new myError(
'transaction already exsist',
400,
5,
'تراکنش قبلا وجود دارد',
'خطا رخ داد'
)
throw error
}
}
return Currencies.findOne({ _id: currencyId })
.then((cur) => {
let CurAbName = ""
if(cur) {
CurAbName = cur.ab_name
switch(CurAbName) {
case "BTC":
checkStatus = () => {
return bitcoin.bitcoinTransferToExchangeById(txId)
.then((result) => {
info = result
})
.catch((err) => {
throw err
})
}
break;
case "ETH":
return etherium.checkTransaction(txId)
.then((transaction) => {
if(transaction && transaction.hash.toString() === txId.toString()) {
let curInWall = _.find(user.wallet, (i) => { return i.currency.toString()=== currencyId.toString()})
if(curInWall) {
curInWall.value += Number(transaction.value)
} else {
}
return
} else {
throw "transaction not valid"
}
})
.catch((err)=>{
console.log("api error: ",err)
})
//
case "TRX":
return tron.validateByTXId(txId)
.then((transaction: any) => {
if(transaction.result) {
const resObj = {
status:"successful",
txValue : transaction
}
return resObj
} else {
const resObj = {
status:"pending",
txValue : transaction
}
}
})
.catch((err) => {
throw(err)
})
// default
}
return Promise.all([checkStatus()])
.then(() => {
if(userHaveDoc) {
userPending.transactions.push({
txId:txId,
currencyId:currencyId,
currencyName:CurAbName,
value:info.txAmount,
type:"id"
})
userPending.save()
.then(() => {
if(info.status === 'Confirmed') {
return SuccessfulTransfers.findOne({ userId: userId }).session(session)
.then(async (userSuccess) => {
if(userSuccess && userSuccess.userId.toString() === userId.toString()) {
userSuccess.transactions.push({
txId,
currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
})
await userSuccess.save()
} else {
const usrSuccess = {
userId:userId,
transactions: [{
txId,
currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
}]
}
await SuccessfulTransfers.create([usrSuccess], { session })
}
return PendingTransfers.findOne({ userId:userId }).session(session)
.then(async (userPendinAfterSave) => {
userPendinAfterSave.transactions = _.filter(userPendinAfterSave.transactions, (i) => { return i.txId.toString() !== txId.toString() })
await userPendinAfterSave.save()
let cur = _.find(user.wallet, (i) => { return i.currency.toString() === currencyId.toString()})
if(cur) {
cur.value +=info.txAmount
await user.save()
} else {
user.wallet.push({
currency: currencyId,
value: info.txAmount
})
await user.save()
}
resObj = {
status: 'successful',
value: info.txAmount
}
}).catch((err)=>{
throw err
})
}).catch((err)=>{
throw err
})
} else {
resObj = {
status: 'pending',
value: info.txAmount
}
}
})
.catch((err) => {
throw err
})
} else {
const usrPending = {
userId:userId,
transactions: [{
txId,
currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
}]
}
PendingTransfers.create([usrPending])
.then(() => {
if(info.status === 'Confirmed') {
return SuccessfulTransfers.findOne({ userId: userId }).session(session)
.then(async (userSuccess) => {
if(userSuccess && userSuccess.userId.toString() === userId.toString()) {
userSuccess.transactions.push({
txId,
currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
})
await userSuccess.save()
} else {
const usrSuccess = {
userId:userId,
transactions: [{
txId,
currencyId,
currencyName: CurAbName,
value: info.txAmount,
type: "id"
}]
}
await SuccessfulTransfers.create([usrSuccess], { session })
}
return PendingTransfers.findOne({ userId:userId }).session(session)
.then(async (userPendinAfterSave) => {
userPendinAfterSave.transactions = _.filter(userPendinAfterSave.transactions, (i) => { return i.txId.toString() !== txId.toString() })
await userPendinAfterSave.save()
let cur = _.find(user.wallet, (i) => { return i.currency.toString() === currencyId.toString()})
if(cur) {
cur.value +=info.txAmount
await user.save()
} else {
user.wallet.push({
currency: currencyId,
value: info.txAmount
})
await user.save()
}
resObj = {
status: 'successful',
value: info.txAmount
}
}).catch((err)=>{
throw err
})
}).catch((err)=>{
throw err
})
} else {
resObj = {
status: 'pending',
value: info.txAmount
}
}
})
.catch((err) => {
throw err
})
}
})
.catch((err) => {
throw err
})
} else {
const error = new myError(
'currency not found',
400,
5,
'ارز مربوطه پیدا نشد.',
'خطا رخ داد'
)
throw error
}
})
.catch((err) => {
throw err
})
})
.catch((err) => {
throw err
})
} else {
const error = new myError(
'user not found',
400,
5,
'کاربر پیدا نشد.',
'خطا رخ داد'
)
throw error
}
})
.catch((err) => {
throw err
})
})
.then(() => {
return resObj
})
.catch((err) => {
throw ("error in with Transaction"+ ":" + err)
})
.finally(() => {
session.endSession()
})
}

109
server/api/walletApi/tron.js Executable file
View File

@@ -0,0 +1,109 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.TRONTransferFrom = exports.validateByTXId = void 0;
var tronWeb = require("tronweb");
// export function TRONTransferTo(userId, systemAccount, userAccount, privateKey, amount){
// User.findOne({ _id : userId })
// .then((user) => {
// if(user && user._id.toString() === userId.toString()){
// const HttpProvider = tronWeb.providers.HttpProvider;
// const fullNode = new HttpProvider("https://api.shasta.trongrid.io");
// const solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
// const eventServer = new HttpProvider("https://api.shasta.trongrid.io");
// const tw = new tronWeb(fullNode,solidityNode,eventServer,privateKey);
// const am = amount * 1000000
// tw.trx.getAccount(userAccount.toString()).then((usrAcc) =>{
// if(usrAcc){
// tw.trx.sendTransaction(systemAccount, am)
// }else{
// const error = "user Tron Account not fount"
// console.log("Error in TRONTransferTo : ", error)
// }
// })
// .catch((err) => console.log(err))
// }else{
// const error = 'user not fount'
// console.log('Error in TRONTransferTo : ', error)
// }
// })
// .catch((err) => console.log('Error in TRONTransferTo : ', err))
// }
function validateByTXId(hash) {
return __awaiter(this, void 0, void 0, function () {
var systemPrivateKey, HttpProvider, fullNode, solidityNode, eventServer, TronWeb;
return __generator(this, function (_a) {
systemPrivateKey = '4a8f251556d19ab6625c0cc012a3c534bf978e6a099d0bb8f42d6539579a10c5';
HttpProvider = tronWeb.providers.HttpProvider;
fullNode = new HttpProvider("https://api.shasta.trongrid.io");
solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
eventServer = new HttpProvider("https://api.shasta.trongrid.io");
TronWeb = new tronWeb(fullNode, solidityNode, eventServer, systemPrivateKey);
console.log("here : ", TronWeb);
TronWeb.trx.getTransaction(hash.toString())
.then(function (transaction) {
return transaction;
})["catch"](function (err) { throw (err); });
return [2 /*return*/];
});
});
}
exports.validateByTXId = validateByTXId;
function TRONTransferFrom(destAccount, am) {
return __awaiter(this, void 0, void 0, function () {
var systemPrivateKey, amount, HttpProvider, fullNode, solidityNode, eventServer, TronWeb;
return __generator(this, function (_a) {
systemPrivateKey = '4a8f251556d19ab6625c0cc012a3c534bf978e6a099d0bb8f42d6539579a10c5';
amount = am * 1000000;
HttpProvider = tronWeb.providers.HttpProvider;
fullNode = new HttpProvider("https://api.shasta.trongrid.io");
solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
eventServer = new HttpProvider("https://api.shasta.trongrid.io");
TronWeb = new tronWeb(fullNode, solidityNode, eventServer, systemPrivateKey);
TronWeb.trx.sendTransaction(destAccount, amount)
.then(function (transaction) {
return transaction;
})["catch"](function (err) {
console.log("Error : ", err);
throw (err);
});
return [2 /*return*/];
});
});
}
exports.TRONTransferFrom = TRONTransferFrom;

80
server/api/walletApi/tron.ts Executable file
View File

@@ -0,0 +1,80 @@
import * as tronWeb from 'tronweb'
// import { Currencies } from '../db/currencies';
// import { User } from '../db/user'
import * as _ from 'lodash'
// export function TRONTransferTo(userId, systemAccount, userAccount, privateKey, amount){
// User.findOne({ _id : userId })
// .then((user) => {
// if(user && user._id.toString() === userId.toString()){
// const HttpProvider = tronWeb.providers.HttpProvider;
// const fullNode = new HttpProvider("https://api.shasta.trongrid.io");
// const solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
// const eventServer = new HttpProvider("https://api.shasta.trongrid.io");
// const tw = new tronWeb(fullNode,solidityNode,eventServer,privateKey);
// const am = amount * 1000000
// tw.trx.getAccount(userAccount.toString()).then((usrAcc) =>{
// if(usrAcc){
// tw.trx.sendTransaction(systemAccount, am)
// }else{
// const error = "user Tron Account not fount"
// console.log("Error in TRONTransferTo : ", error)
// }
// })
// .catch((err) => console.log(err))
// }else{
// const error = 'user not fount'
// console.log('Error in TRONTransferTo : ', error)
// }
// })
// .catch((err) => console.log('Error in TRONTransferTo : ', err))
// }
export async function validateByTXId(hash){
const systemPrivateKey = '4a8f251556d19ab6625c0cc012a3c534bf978e6a099d0bb8f42d6539579a10c5'
const HttpProvider = tronWeb.providers.HttpProvider;
const fullNode = new HttpProvider("https://api.shasta.trongrid.io");
const solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
const eventServer = new HttpProvider("https://api.shasta.trongrid.io");
const TronWeb = new tronWeb(fullNode,solidityNode,eventServer,systemPrivateKey);
console.log("here : ", TronWeb)
TronWeb.trx.getTransaction(hash.toString())
.then((transaction) => {
return transaction
})
.catch((err) => {throw(err)})
}
export async function TRONTransferFrom(destAccount, am){
const systemPrivateKey = '4a8f251556d19ab6625c0cc012a3c534bf978e6a099d0bb8f42d6539579a10c5'
const amount = am * 1000000
const HttpProvider = tronWeb.providers.HttpProvider;
const fullNode = new HttpProvider("https://api.shasta.trongrid.io");
const solidityNode = new HttpProvider("https://api.shasta.trongrid.io");
const eventServer = new HttpProvider("https://api.shasta.trongrid.io");
const TronWeb = new tronWeb(fullNode,solidityNode,eventServer,systemPrivateKey);
TronWeb.trx.sendTransaction(destAccount, amount)
.then((transaction) => {
return transaction
})
.catch((err) => {
console.log("Error : ", err)
throw(err)
})
}