UNPKG

@bluefin-exchange/bluefin-v2-client

Version:

The Bluefin client Library allows traders to sign, create, retrieve and listen to orders on Bluefin Exchange.

245 lines 9.38 kB
"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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateRandomNumber = void 0; exports.getKeyPairFromSeed = getKeyPairFromSeed; exports.getSignerFromSeed = getSignerFromSeed; exports.readFile = readFile; exports.setupTestAccounts = setupTestAccounts; exports.createWallet = createWallet; exports.combineAndEncode = combineAndEncode; exports.throwCustomError = throwCustomError; exports.filterDelistedMarkets = filterDelistedMarkets; exports.isMainnet = isMainnet; exports.getSpotDeploymentConfig = getSpotDeploymentConfig; exports.getProDeploymentConfig = getProDeploymentConfig; const library_sui_1 = require("@firefly-exchange/library-sui"); const fs_1 = __importDefault(require("fs")); const index_1 = require("@firefly-exchange/library-sui/index"); const cryptography_1 = require("@mysten/sui/cryptography"); const interfaces_1 = __importDefault(require("../src/interfaces")); const platform_1 = require("../src/platform"); // Import the deployment files directly const spotDeployment_json_1 = __importDefault(require("../spotDeployment.json")); const proDeployment_json_1 = __importDefault(require("../proDeployment.json")); let path; if (platform_1.isNode) { path = require("path"); } /** * Generates random number * @param multiplier number to multiply with random number generated * @returns random number */ const generateRandomNumber = (multiplier) => { return Math.floor((Date.now() + Math.random() + Math.random()) * multiplier); }; exports.generateRandomNumber = generateRandomNumber; function getKeyPairFromSeed(seed, scheme = "Secp256k1") { switch (scheme) { case "ED25519": return library_sui_1.Ed25519Keypair.deriveKeypair(seed); case "Secp256k1": return library_sui_1.Secp256k1Keypair.deriveKeypair(seed); default: throw new Error("Provided scheme is invalid"); } } function getSignerFromSeed(seed) { return getKeyPairFromSeed(seed); } function readFileServer(filePath) { try { // Try to resolve the file path relative to the current working directory const resolvedPath = path.resolve(process.cwd(), filePath); if (fs_1.default.existsSync(resolvedPath)) { return JSON.parse(fs_1.default.readFileSync(resolvedPath, "utf-8")); } // If not found, try to resolve relative to the package root const packageRoot = path.resolve(__dirname, ".."); const packagePath = path.resolve(packageRoot, filePath); if (fs_1.default.existsSync(packagePath)) { return JSON.parse(fs_1.default.readFileSync(packagePath, "utf-8")); } // If still not found, try to resolve relative to the src directory const srcPath = path.resolve(__dirname, filePath); if (fs_1.default.existsSync(srcPath)) { return JSON.parse(fs_1.default.readFileSync(srcPath, "utf-8")); } // If all else fails, return the imported JSON if (filePath === "spotDeployment.json") { return spotDeployment_json_1.default; } if (filePath === "proDeployment.json") { return proDeployment_json_1.default; } console.warn(`Configuration file not found at any of these paths: - ${resolvedPath} - ${packagePath} - ${srcPath}`); return {}; } catch (error) { console.error("Error reading configuration file:", error); return {}; } } function readFileBrowser(filePath) { try { if (filePath === "spotDeployment.json") { return spotDeployment_json_1.default; } if (filePath === "proDeployment.json") { return proDeployment_json_1.default; } return {}; } catch (error) { console.error("Error reading deployment data in browser:", error); return {}; } } function readFile(filePath) { if (typeof window === "undefined") { return readFileServer(filePath); } return readFileBrowser(filePath); } function setupTestAccounts(deployerWallet, testWallets, faucetURL) { return __awaiter(this, void 0, void 0, function* () { const mintAmount = 1000000000; // eslint-disable-next-line no-restricted-syntax for (const wallet of testWallets) { try { // eslint-disable-next-line no-await-in-loop yield library_sui_1.Faucet.requestSUI(wallet.privateAddress, faucetURL); } catch (e) { console.log(e); } } // eslint-disable-next-line no-restricted-syntax for (const wallet of testWallets) { // eslint-disable-next-line no-await-in-loop yield deployerWallet.mintUSDC({ amount: (0, library_sui_1.toBigNumberStr)(mintAmount.toString(), 6), to: wallet.privateAddress, gasBudget: 10000000, }); } return true; }); } /** * @description * Generate a new wallet * @returns private key and public address * */ function createWallet() { const wallet = library_sui_1.Ed25519Keypair.generate(); const signerKey = wallet.getSecretKey(); const keyPair = (0, cryptography_1.decodeSuiPrivateKey)(signerKey); const publicAddress = wallet.toSuiAddress(); return { privateKey: (0, index_1.toHex)(keyPair.secretKey), publicAddress, }; } function combineAndEncode({ bytes, signature }) { // serialize const separator = "||||"; // Choose a separator that won't appear in txBytes or signature const combinedData = `${bytes}${separator}${signature}`; // Encode to hex for transmission const encodedData = Buffer.from(combinedData, "utf-8").toString("hex"); return encodedData; } /** * Utility function to throw a CustomError. * * @param {Error} error - The original error object. * @param {Errors} code - The error code. * @param {string} [name] - Optional custom name for the error. * @throws {CustomError} */ function throwCustomError({ error, code, extra, }) { if (typeof error === "string") error = new Error(error); throw new interfaces_1.default(error, code, extra); } // Helper function to check if exchangeInfo.data is an object or array function filterDelistedMarkets(exchangeInfo) { if (!(exchangeInfo === null || exchangeInfo === void 0 ? void 0 : exchangeInfo.data)) { return []; } const status = "DELISTED"; if (Array.isArray(exchangeInfo.data)) { const filtered = exchangeInfo.data .filter((market) => { return market.status === status; }) .map((market) => market.symbol); return filtered; } else if (typeof exchangeInfo.data === "object") { return exchangeInfo.data.status === status ? [exchangeInfo.data.symbol] : []; } return []; } /** * Determines if the network is mainnet based on ExtendedNetwork * @param network ExtendedNetwork * @returns boolean indicating if network is mainnet */ function isMainnet(network) { var _a, _b; return (((_a = network.name) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes("production")) || ((_b = network.apiGateway) === null || _b === void 0 ? void 0 : _b.toLowerCase().includes("sui-prod")) || false); } /** * Reads spot deployment configuration based on network type * @param network ExtendedNetwork * @returns IBluefinSpotContracts configuration */ function getSpotDeploymentConfig(network) { try { const networkType = isMainnet(network) ? "mainnet" : "testnet"; const spotConfig = readFile("spotDeployment.json"); if (!spotConfig || !spotConfig[networkType]) { throw new Error(`No configuration found for network: ${networkType}`); } return spotConfig[networkType]; } catch (error) { console.error("Error reading spot deployment config:", error); throw error; } } function getProDeploymentConfig(network) { try { const networkType = isMainnet(network) ? "mainnet" : "testnet"; const proConfig = readFile("proDeployment.json"); if (!proConfig || !proConfig[networkType]) { throw new Error(`No configuration found for network: ${networkType}`); } return proConfig[networkType]; } catch (error) { console.error("Error reading pro deployment config:", error); throw error; } } //# sourceMappingURL=utils.js.map