Skip to content

Commit

Permalink
🔀 Merge branch 'master' into feature/likernft
Browse files Browse the repository at this point in the history
# Conflicts:
#	src/util/cosmos/iscn.js
#	src/util/cosmos/tx.js
  • Loading branch information
williamchong committed Jul 20, 2022
2 parents becb1b5 + 7744263 commit 40053ed
Show file tree
Hide file tree
Showing 13 changed files with 154 additions and 71 deletions.
3 changes: 3 additions & 0 deletions config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ config.FIRESTORE_ISCN_INFO_ROOT = process.env.FIRESTORE_ISCN_INFO_ROOT;
config.COSMOS_LCD_INDEXER_ENDPOINT = 'https://node.testnet.like.co';
config.COSMOS_LCD_ENDPOINT = 'https://node.testnet.like.co';
config.COSMOS_RPC_ENDPOINT = 'https://node.testnet.like.co/rpc/';
config.COSMOS_SIGNING_RPC_ENDPOINT = 'https://node.testnet.like.co/rpc/';
config.COSMOS_CHAIN_ID = 'likecoin-public-testnet-5';
config.ISCN_DEV_LCD_ENDPOINT = 'localhost:1317';
config.ISCN_DEV_CHAIN_ID = 'iscn-dev-chain';
Expand Down Expand Up @@ -89,4 +90,6 @@ config.APP_SERVER = 'likecoin-api-pulic';
config.CMC_PRO_API_KEY = '';
config.CMC_API_CACHE_S = 300;

config.IS_CHAIN_UPGRADING = false;

module.exports = config;
56 changes: 44 additions & 12 deletions src/routes/iscn/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import BigNumber from 'bignumber.js';
import publisher from '../../util/gcloudPub';
import { IS_TESTNET, PUBSUB_TOPIC_MISC } from '../../constant';
import { jwtAuth } from '../../middleware/jwt';
import { sleep } from '../../util/misc';
import {
getISCNSigningClient,
getISCNQueryClient,
Expand All @@ -23,7 +24,7 @@ import { checkFileValid, convertMulterFiles } from '../../util/api/arweave';
import { estimateARPrices, convertARPricesToLIKE, uploadFilesToArweave } from '../../util/arweave';
import { getIPFSHash, uploadFilesToIPFS } from '../../util/ipfs';

const { ARWEAVE_LIKE_TARGET_ADDRESS } = require('../../../config/config');
const { ARWEAVE_LIKE_TARGET_ADDRESS, IS_CHAIN_UPGRADING } = require('../../../config/config');

const maxSize = 100 * 1024 * 1024; // 100 MB

Expand Down Expand Up @@ -106,15 +107,6 @@ async function handleRegisterISCN(req, res, next) {
address,
accountNumber,
} = res.locals.signingInfo;
const createIscnSigningFunction = ({ sequence }) => signingClient.createISCNRecord(
address,
ISCNPayload, {
accountNumber,
sequence,
chainId: COSMOS_CHAIN_ID,
broadcast: false,
},
);

if (req.query.estimate) {
const uploadPrice = req.uploadPrice || 0;
Expand All @@ -130,6 +122,21 @@ async function handleRegisterISCN(req, res, next) {
return;
}

if (IS_CHAIN_UPGRADING) {
res.status(400).send('CHAIN_UPGRADING');
return;
}

const createIscnSigningFunction = ({ sequence }) => signingClient.createISCNRecord(
address,
ISCNPayload, {
accountNumber,
sequence,
chainId: COSMOS_CHAIN_ID,
broadcast: false,
},
);

const [iscnFee, iscnRes] = await Promise.all([
signingClient.estimateISCNTxFee(address, ISCNPayload),
sendTransactionWithSequence(address, createIscnSigningFunction),
Expand All @@ -142,7 +149,26 @@ async function handleRegisterISCN(req, res, next) {
} = iscnRes;
const gasLIKE = new BigNumber(gasWanted).multipliedBy(DEFAULT_GAS_PRICE).shiftedBy(-9);
let totalLIKE = gasLIKE.plus(iscnLike);
const [iscnId] = await queryClient.queryISCNIdsByTx(iscnTxHash);
let iscnId;
const QUERY_RETRY_LIMIT = 10;
let tryCount = 0;
while (!iscnId && tryCount < QUERY_RETRY_LIMIT) {
/* eslint-disable no-await-in-loop */
([iscnId] = await queryClient.queryISCNIdsByTx(iscnTxHash));
if (!iscnId) await sleep(2000);
tryCount += 1;
/* eslint-enable no-await-in-loop */
}

// TODO: remove iscn debug
if (iscnId) {
console.log(`ISCN ID: ${iscnId}`);
} else if (iscnTxHash) {
console.error(`Cannot find ISCN ID for TX ${iscnTxHash}`);
} else {
console.error('Cannot find ISCN ID and ISCN TX');
}

publisher.publish(PUBSUB_TOPIC_MISC, req, {
logType: 'ISCNFreeRegister',
txHash: iscnTxHash,
Expand All @@ -167,7 +193,8 @@ async function handleRegisterISCN(req, res, next) {
});

const wallet = likeWallet || cosmosWallet;
if (isClaim && wallet) {
if (isClaim && iscnId && wallet) {
// TODO handle missing iscnId by refetch?
const transferSigningFunction = ({ sequence }) => signingClient.changeISCNOwnership(
address,
wallet,
Expand Down Expand Up @@ -261,6 +288,11 @@ router.post('/upload',
next();
return;
}
if (IS_CHAIN_UPGRADING) {
res.status(400).send('CHAIN_UPGRADING');
return;
}

const amount = new BigNumber(LIKE).shiftedBy(9).toFixed();
const signingClient = await getISCNSigningClient();
if (!res.locals.signingInfo) {
Expand Down
25 changes: 0 additions & 25 deletions src/routes/misc/price.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
import axios from 'axios';
import { Router } from 'express';
import https from 'https';
import fs from 'fs';

import {
COINGECKO_PRICE_URL,
LIKE_DEFAULT_PRICE,
} from '../../constant';
import {
CMC_API_CACHE_S,
BITASSET_API_BASE_URL,
} from '../../../config/config';

const router = Router();
Expand All @@ -19,13 +16,6 @@ const USDTWD = 30.51;
const LOW_THRESHOLD_PRICE_TWD = 0.03;
const LOW_THRESHOLD_PRICE_USD = LOW_THRESHOLD_PRICE_TWD / USDTWD;

const bitassetAgent = new https.Agent({ ca: fs.readFileSync('./ssl/bitasset.pem') });
const bitassetAxios = axios.create({
baseURL: BITASSET_API_BASE_URL || 'https://api.bitasset.pro',
timeout: 20000,
httpsAgent: bitassetAgent,
});

router.get('/price', async (req, res) => {
const { currency = 'usd' } = req.query;
let price;
Expand All @@ -34,21 +24,6 @@ router.get('/price', async (req, res) => {
axios.get(COINGECKO_PRICE_URL)
.then(r => r.data.market_data.current_price[currency])
.catch(() => undefined),
bitassetAxios.get('/v1/cash/public/query-depth?contractId=152') // LIKETWD
.then((r) => {
if (currency === 'usd') {
return parseFloat(r.data.data.lastPrice) / USDTWD;
}
if (currency === 'twd') {
return parseFloat(r.data.data.lastPrice);
}
throw new Error('Undefined BitAsset currency');
})
.catch((err) => {
const msg = (err.response && err.response.data) || err;
console.error(msg);
return undefined;
}),
]);
const validPrices = prices.filter(p => !isNaN(p)); // eslint-disable-line no-restricted-globals
if (!validPrices.length) {
Expand Down
25 changes: 22 additions & 3 deletions src/routes/users/getPublicInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import {
import { ValidationError } from '../../util/ValidationError';
import {
checkAddressValid,
checkCosmosAddressValid,
filterUserDataMin,
} from '../../util/ValidationHelper';
import {
getUserWithCivicLikerProperties,
formatUserCivicLikerProperies,
} from '../../util/api/users/getPublicInfo';

const router = Router();
Expand Down Expand Up @@ -36,10 +38,27 @@ router.get('/id/:id/min', async (req, res, next) => {
router.get('/addr/:addr/min', async (req, res, next) => {
try {
const { addr } = req.params;
if (!checkAddressValid(addr)) throw new ValidationError('Invalid address');
const query = await dbRef.where('wallet', '==', addr).get();
const { type } = req.query;
let types = [];
if (type) {
types = type.split(',');
}
let field;
if (checkAddressValid(addr)) {
field = 'wallet';
} else if (checkCosmosAddressValid(addr, 'like')) {
field = 'likeWallet';
} else if (checkCosmosAddressValid(addr, 'cosmos')) {
field = 'cosmosWallet';
} else {
throw new ValidationError('Invalid address');
}
const query = await dbRef.where(field, '==', addr).limit(1).get();
if (query.docs.length > 0) {
res.sendStatus(200);
res.set('Cache-Control', 'public, max-age=30');
const userDoc = query.docs[0];
const payload = formatUserCivicLikerProperies(userDoc.id, userDoc.data());
res.json(filterUserDataMin(payload, types));
} else {
res.sendStatus(404);
}
Expand Down
2 changes: 2 additions & 0 deletions src/util/ValidationHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ export function filterUserDataMin(userObject, types = []) {
isSubscribedCivicLiker,
isCivicLikerTrial,
civicLikerSince,
description,
} = userObject;
const output = {
user,
Expand All @@ -110,6 +111,7 @@ export function filterUserDataMin(userObject, types = []) {
isCivicLikerTrial,
isSubscribedCivicLiker,
civicLikerSince,
description,
};
if (types.includes('payment')) {
output.paymentRedirectWhiteList = userObject.paymentRedirectWhiteList;
Expand Down
19 changes: 11 additions & 8 deletions src/util/api/users/getPublicInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,9 @@ import {
userCollection as dbRef,
} from '../../firebase';

export async function getUserWithCivicLikerProperties(id) {
const [userDoc] = await Promise.all([
dbRef.doc(id).get(),
]);
if (!userDoc.exists) return null;

const payload = userDoc.data();
const { avatar, civicLiker } = payload;
export function formatUserCivicLikerProperies(id, data) {
const { avatar, civicLiker } = data;
const payload = data;
payload.user = id;
if (!avatar) {
payload.avatar = AVATAR_DEFAULT_PATH;
Expand Down Expand Up @@ -45,7 +40,15 @@ export async function getUserWithCivicLikerProperties(id) {
payload.isExpiredCivicLiker = true;
}
}
return payload;
}

export async function getUserWithCivicLikerProperties(id) {
const userDoc = await dbRef.doc(id).get();
if (!userDoc.exists) return null;

const data = userDoc.data();
const payload = formatUserCivicLikerProperies(id, data);
return payload;
}

Expand Down
37 changes: 19 additions & 18 deletions src/util/api/users/register.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { sendVerificationEmail } from '../../sendgrid';
// import { sendVerificationEmail } from '../../sendgrid';
import {
PUBSUB_TOPIC_MISC,
MIN_USER_ID_LENGTH,
Expand Down Expand Up @@ -34,7 +34,7 @@ import {
NEW_USER_BONUS_COOLDOWN,
} from '../../../../config/config';

const uuidv4 = require('uuid/v4');
// const uuidv4 = require('uuid/v4');

function getBool(value = false) {
if (typeof value === 'string') {
Expand Down Expand Up @@ -77,7 +77,7 @@ export async function suggestAvailableUserName(username = '') {
export async function handleUserRegistration({
payload,
req,
res,
// res,
isPlatformDelegated = false,
}) {
const {
Expand Down Expand Up @@ -198,22 +198,23 @@ export async function handleUserRegistration({
}

// TODO: trigger verify email via authcore?
if (!(isEmailVerified || isEmailBlacklisted || isEmailInvalid)) {
// Send verify email
createObj.lastVerifyTs = Date.now();
createObj.verificationUUID = uuidv4();
// TODO: reactivate after spam investigation
// if (!(isEmailVerified || isEmailBlacklisted || isEmailInvalid)) {
// // Send verify email
// createObj.lastVerifyTs = Date.now();
// createObj.verificationUUID = uuidv4();

try {
await sendVerificationEmail(res, {
email,
displayName,
verificationUUID: createObj.verificationUUID,
}, createObj.referrer);
} catch (err) {
console.error(err);
// Do nothing
}
}
// try {
// await sendVerificationEmail(res, {
// email,
// displayName,
// verificationUUID: createObj.verificationUUID,
// }, createObj.referrer);
// } catch (err) {
// console.error(err);
// // Do nothing
// }
// }
}

if (phone) {
Expand Down
7 changes: 3 additions & 4 deletions src/util/cosmos/iscn.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@
import { DirectSecp256k1Wallet } from '@cosmjs/proto-signing';
import BigNumber from 'bignumber.js';
import { ISCNQueryClient, ISCNSigningClient } from '@likecoin/iscn-js';
export { parseTxInfoFromIndexedTx } from '@likecoin/iscn-js/dist/messages/parsing';
import { getAccountInfo, isValidAddress, convertAddressPrefix } from '.';
import { getUserWithCivicLikerProperties } from '../api/users/getPublicInfo';
import { COSMOS_PRIVATE_KEY } from '../../../config/secret';
import { COSMOS_RPC_ENDPOINT } from '../../../config/config';

export { parseTxInfoFromIndexedTx } from '@likecoin/iscn-js/dist/messages/parsing';
import { COSMOS_RPC_ENDPOINT, COSMOS_SIGNING_RPC_ENDPOINT } from '../../../config/config';

let queryClient = null;
let signingClient = null;
Expand All @@ -28,7 +27,7 @@ export async function createISCNSigningClient(privateKey) {
const signer = await DirectSecp256k1Wallet.fromKey(privateKeyBytes, 'like');
const [wallet] = await signer.getAccounts();
const client = new ISCNSigningClient();
await client.connectWithSigner(COSMOS_RPC_ENDPOINT, signer);
await client.connectWithSigner(COSMOS_SIGNING_RPC_ENDPOINT, signer);
return { client, wallet };
}

Expand Down
9 changes: 8 additions & 1 deletion src/util/cosmos/tx.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { PUBSUB_TOPIC_MISC } from '../../constant';
const {
COSMOS_DENOM,
COSMOS_RPC_ENDPOINT,
COSMOS_SIGNING_RPC_ENDPOINT,
COSMOS_GAS_PRICE,
} = require('../../../config/config');

Expand All @@ -22,6 +23,12 @@ export const DEFAULT_TRANSFER_GAS = 80000;
export const DEFAULT_CHANGE_ISCN_OWNERSHIP_GAS = 59714;

let stargateClient = null;
let broadcastClient = null;

async function getBroadcastClient() {
if (!broadcastClient) broadcastClient = await StargateClient.connect(COSMOS_SIGNING_RPC_ENDPOINT);
return broadcastClient;
}

async function getClient() {
if (!stargateClient) stargateClient = await StargateClient.connect(COSMOS_RPC_ENDPOINT);
Expand Down Expand Up @@ -79,7 +86,7 @@ async function computeTransactionHash(signedTx) {
}

async function internalSendTransaction(signedTx, c) {
const client = c || await getClient();
const client = c || await getBroadcastClient();
const txBytes = TxRaw.encode(signedTx).finish();
try {
const res = await client.broadcastTx(txBytes);
Expand Down
3 changes: 3 additions & 0 deletions test/api/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export const {
email: testingEmail1,
wallet: testingWallet1,
cosmosWallet: testingCosmosWallet1,
likeWallet: testingLikeWallet1,
locale: testingUser1Locale,
creatorPitch: testingUser1CreatorPitch,
} = userData.users[0];
Expand All @@ -26,6 +27,8 @@ export const {
} = userData.users[1];
export const invalidWallet = '4b25758E41f9240C8EB8831cEc7F1a02686387fa';
export const testingWallet3 = '0x9113EC0624802E6BB2b13d7e123C91Aa5D130314'; // wallet that is not used
export const testingCosmosWallet3 = 'cosmos154xjc0r3770jahjnjs46qrdtezqm9htplr0cjl'; // wallet that is not used
export const testingLikeWallet3 = 'like154xjc0r3770jahjnjs46qrdtezqm9htpvln63y'; // wallet that is not used
export const {
id: testingUser4,
wallet: testingWallet4,
Expand Down
Loading

0 comments on commit 40053ed

Please sign in to comment.