Skip to content

Commit

Permalink
Merge pull request #13 from oraichain/chore/refactor
Browse files Browse the repository at this point in the history
chore: refactor
  • Loading branch information
meomeocoj authored Mar 2, 2024
2 parents 0c23f9c + 3da4f7d commit 2c42e73
Show file tree
Hide file tree
Showing 16 changed files with 207 additions and 126 deletions.
5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"private": true,
"scripts": {
"postinstall": "patch-package",
"build": "tsc -p",
"build": "lerna run build --concurrency 1",
"test": "jest",
"deploy": "yarn publish --access public",
"docs": "typedoc --entryPointStrategy expand --name 'Orai Margin Trade SDK' --readme none --tsconfig packages/contracts-sdk/tsconfig.json packages/contracts-sdk/src"
Expand All @@ -17,9 +17,6 @@
"dependencies": {
"@cosmjs/amino": "^0.31",
"@cosmjs/cosmwasm-stargate": "^0.31.0",
"@oraichain/oraitrading-common": "^0.0.4",
"@oraichain/oraimargin-contracts-build": "^1.0.32",
"@oraichain/oraimargin-contracts-sdk": "^1.0.34",
"@types/node-cron": "^3.0.10",
"discord.js": "^14.13.0",
"node-cron": "^3.0.2"
Expand Down
6 changes: 6 additions & 0 deletions packages/common/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,11 @@
"name": "@oraichain/oraitrading-common",
"version": "0.0.4",
"main": "build/index.js",
"files": [
"build/"
],
"scripts": {
"build": "tsc -p tsconfig.json"
},
"license": "MIT"
}
99 changes: 69 additions & 30 deletions packages/common/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { SigningCosmWasmClient } from '@cosmjs/cosmwasm-stargate';
import { stringToPath } from '@cosmjs/crypto';
import { DirectSecp256k1HdWallet } from '@cosmjs/proto-signing';
import { GasPrice } from '@cosmjs/stargate';
import crypto from 'crypto';
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { stringToPath } from "@cosmjs/crypto";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { GasPrice } from "@cosmjs/stargate";
import crypto from "crypto";

export type UserWallet = { address: string; client: SigningCosmWasmClient };
const truncDecimals = 6;
Expand All @@ -14,7 +14,10 @@ export type RetryOptions = {
callback?: (retry: number) => void;
};

const fetchRetry = async (url: RequestInfo | URL, opts: RequestInit & RetryOptions = {}) => {
const fetchRetry = async (
url: RequestInfo | URL,
opts: RequestInit & RetryOptions = {}
) => {
let { retry = 3, callback, timeout = 30000, ...init } = opts;
init.signal = AbortSignal.timeout(timeout);
while (retry > 0) {
Expand All @@ -35,38 +38,57 @@ export const delay = (milliseconds: number) => {
};

export const encrypt = (password: string, val: string) => {
const hashedPassword = crypto.createHash('sha256').update(password).digest();
const hashedPassword = crypto.createHash("sha256").update(password).digest();
const IV = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', hashedPassword, IV);
return Buffer.concat([IV, cipher.update(val), cipher.final()]).toString('base64');
const cipher = crypto.createCipheriv("aes-256-cbc", hashedPassword, IV);
return Buffer.concat([IV, cipher.update(val), cipher.final()]).toString(
"base64"
);
};

export const decrypt = (password: string, val: string) => {
const hashedPassword = crypto.createHash('sha256').update(password).digest();
const encryptedText = Buffer.from(val, 'base64');
const hashedPassword = crypto.createHash("sha256").update(password).digest();
const encryptedText = Buffer.from(val, "base64");
const IV = encryptedText.subarray(0, 16);
const encrypted = encryptedText.subarray(16);
const decipher = crypto.createDecipheriv('aes-256-cbc', hashedPassword, IV);
return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString();
const decipher = crypto.createDecipheriv("aes-256-cbc", hashedPassword, IV);
return Buffer.concat([
decipher.update(encrypted),
decipher.final(),
]).toString();
};

export const getRandomRange = (min: number, max: number): number => {
return ((Math.random() * (max - min + 1)) << 0) + min;
};

export const getOraclePrice = async (token: string, url?: string): Promise<number> => {
const response = await fetchRetry(url ?? `https://api.orchai.io/lending/mainnet/token/${token}`);
export const getOraclePrice = async (
token: string,
url?: string
): Promise<number> => {
const response = await fetchRetry(
url ?? `https://api.orchai.io/lending/mainnet/token/${token}`
);
const result = await response.json();
return result.current_price;
};

export const getCoingeckoPrice = async (token: "oraichain-token" | "airight", url?: string): Promise<number> => {
const response = await fetchRetry(url ?? `https://price.market.orai.io/simple/price?ids=${token}&vs_currencies=usd`);
export const getCoingeckoPrice = async (
token: "oraichain-token" | "airight",
url?: string
): Promise<number> => {
const response = await fetchRetry(
url ??
`https://price.market.orai.io/simple/price?ids=${token}&vs_currencies=usd`
);
const result = await response.json();
return result[token].usd;
};

export const getPriceFeed = async (token: string, url?: string): Promise<number> => {
export const getPriceFeed = async (
token: string,
url?: string
): Promise<number> => {
console.log("getPriceFeed url", url);
const response = await fetchRetry(url);
const priceData = await response.json();
Expand All @@ -79,7 +101,7 @@ export const getPriceFeed = async (token: string, url?: string): Promise<number>
};

export const validateNumber = (amount: number | string): number => {
if (typeof amount === 'string') return validateNumber(Number(amount));
if (typeof amount === "string") return validateNumber(Number(amount));
if (Number.isNaN(amount) || !Number.isFinite(amount)) return 0;
return amount;
};
Expand All @@ -91,7 +113,10 @@ export const toDecimals = (num: number, decimals: number = 9): string => {
// decimals always >= 6
export const toAmount = (amount: number, decimals = 6): bigint => {
const validatedAmount = validateNumber(amount);
return BigInt(Math.trunc(validatedAmount * atomic)) * BigInt(10 ** (decimals - truncDecimals));
return (
BigInt(Math.trunc(validatedAmount * atomic)) *
BigInt(10 ** (decimals - truncDecimals))
);
};

// bigint abs
Expand All @@ -108,19 +133,23 @@ export async function setupWallet(
cosmwasmClient?: SigningCosmWasmClient
): Promise<UserWallet> {
if (!mnemonic || mnemonic.length < 48) {
throw new Error('Must set MNEMONIC to a 12 word phrase');
throw new Error("Must set MNEMONIC to a 12 word phrase");
}
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
hdPaths: [stringToPath(config.hdPath ?? "m/44'/118'/0'/0/0")],
prefix: config.prefix ?? 'orai'
prefix: config.prefix ?? "orai",
});
const [firstAccount] = await wallet.getAccounts();
const address = firstAccount.address;
const client =
cosmwasmClient ??
(await SigningCosmWasmClient.connectWithSigner(config.rpcUrl || 'https://rpc.orai.io', wallet, {
gasPrice: GasPrice.fromString(`${config.gasPrices ?? '0.001'}orai`)
}));
(await SigningCosmWasmClient.connectWithSigner(
config.rpcUrl || "https://rpc.orai.io",
wallet,
{
gasPrice: GasPrice.fromString(`${config.gasPrices ?? "0.001"}orai`),
}
));

return { address, client };
}
Expand All @@ -129,16 +158,26 @@ export function getDifferencePercentage(a: number, b: number) {
return Math.abs((100 * (a - b)) / b);
}

export const toDisplay = (amount: string | bigint, sourceDecimals = 6, desDecimals = 6): number => {
export const toDisplay = (
amount: string | bigint,
sourceDecimals = 6,
desDecimals = 6
): number => {
if (!amount) return 0;
if (typeof amount === "string" && amount.indexOf(".") !== -1) amount = amount.split(".")[0];
if (typeof amount === "string" && amount.indexOf(".") !== -1)
amount = amount.split(".")[0];
try {
// guarding conditions to prevent crashing
const validatedAmount = typeof amount === "string" ? BigInt(amount || "0") : amount;
const validatedAmount =
typeof amount === "string" ? BigInt(amount || "0") : amount;
const displayDecimals = Math.min(truncDecimals, desDecimals);
const returnAmount = validatedAmount / BigInt(10 ** (sourceDecimals - displayDecimals));
const returnAmount =
validatedAmount / BigInt(10 ** (sourceDecimals - displayDecimals));
// save calculation by using cached atomic
return Number(returnAmount) / (displayDecimals === truncDecimals ? atomic : 10 ** displayDecimals);
return (
Number(returnAmount) /
(displayDecimals === truncDecimals ? atomic : 10 ** displayDecimals)
);
} catch {
return 0;
}
Expand Down
10 changes: 3 additions & 7 deletions packages/common/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@
"declaration": true,
"rootDir": "src"
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules/"
]
}
"include": ["src/**/*.ts"],
"exclude": ["node_modules/"]
}
3 changes: 3 additions & 0 deletions packages/contracts-build/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@
"license": "MIT",
"dependencies": {
"@oraichain/oraimargin-contracts-sdk": "^1.0.34"
},
"scripts": {
"build": "tsc -p tsconfig.json"
}
}
5 changes: 4 additions & 1 deletion packages/contracts-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@
"files": [
"build/"
],
"license": "MIT"
"license": "MIT",
"scripts": {
"build": "tsc -p tsconfig.json"
}
}
4 changes: 4 additions & 0 deletions packages/priceFeed/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@
"main": "build/cli.js",
"bin": "build/cli.js",
"license": "MIT",
"files": [
"build/"
],
"scripts": {
"start": "ts-node src/cli.ts",
"build": "ncc build src/cli.ts --no-source-map-register -t -m"
},
"dependencies": {
"@oraichain/oraitrading-common": "^0.0.4",
"@cosmjs/tendermint-rpc": "^0.31.0",
"@oraichain/common-contracts-build": "^1.0.26",
"@oraichain/common-contracts-sdk": "^1.0.31",
Expand Down
6 changes: 6 additions & 0 deletions packages/tp_sl_lq/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@
"main": "build/cli.js",
"bin": "build/cli.js",
"license": "MIT",
"files": [
"build/"
],
"scripts": {
"start": "ts-node src/cli.ts",
"build": "ncc build src/cli.ts --no-source-map-register -t -m"
},
"dependencies": {
"@oraichain/oraimargin-contracts-sdk": "^1.0.35",
"@oraichain/oraimargin-contracts-build": "^1.0.32",
"@oraichain/oraitrading-common": "^0.0.4",
"@cosmjs/tendermint-rpc": "^0.31.0",
"@oraichain/common-contracts-build": "^1.0.26",
"@oraichain/common-contracts-sdk": "^1.0.31",
Expand Down
Loading

0 comments on commit 2c42e73

Please sign in to comment.