UNPKG

@proton/ccxt

Version:

A JavaScript / TypeScript / Python / C# / PHP cryptocurrency trading library with support for 130+ exchanges

148 lines (145 loc) 6.01 kB
// ---------------------------------------------------------------------------- // PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: // https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code // EDIT THE CORRESPONDENT .ts FILE INSTEAD /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ // We use `globalThis.crypto`, but node.js versions earlier than v19 don't // declare it in global scope. For node.js, package.json#exports field mapping // rewrites import from `crypto` to `cryptoNode`, which imports native module. // Makes the utils un-importable in browsers without a bundler. // Once node.js 18 is deprecated, we can just drop the import. import { crypto } from './crypto.js'; // Cast array to different type export const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); export const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); // Cast array to view export const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); // The rotate right (circular right shift) operation for uint32 export const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); // big-endian hardware is rare. Just in case someone still decides to run hashes: // early-throw an error because we don't support BE yet. export const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; if (!isLE) throw new Error('Non little-endian hardware is not supported'); const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0')); /** * @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef])) // 'deadbeef' */ export function bytesToHex(uint8a) { // pre-caching improves the speed 6x if (!(uint8a instanceof Uint8Array)) throw new Error('Uint8Array expected'); let hex = ''; for (let i = 0; i < uint8a.length; i++) { hex += hexes[uint8a[i]]; } return hex; } /** * @example hexToBytes('deadbeef') // Uint8Array.from([0xde, 0xad, 0xbe, 0xef]) */ export function hexToBytes(hex) { if (typeof hex !== 'string') { throw new TypeError('hexToBytes: expected string, got ' + typeof hex); } if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex'); const array = new Uint8Array(hex.length / 2); for (let i = 0; i < array.length; i++) { const j = i * 2; const hexByte = hex.slice(j, j + 2); const byte = Number.parseInt(hexByte, 16); if (Number.isNaN(byte) || byte < 0) throw new Error('Invalid byte sequence'); array[i] = byte; } return array; } // There is no setImmediate in browser and setTimeout is slow. // call of async fn will return Promise, which will be fullfiled only on // next scheduler queue processing step and this is exactly what we need. export const nextTick = async () => { }; // Returns control to thread each 'tick' ms to avoid blocking export async function asyncLoop(iters, tick, cb) { let ts = Date.now(); for (let i = 0; i < iters; i++) { cb(i); // Date.now() is not monotonic, so in case if clock goes backwards we return return control too const diff = Date.now() - ts; if (diff >= 0 && diff < tick) continue; await nextTick(); ts += diff; } } export function utf8ToBytes(str) { if (typeof str !== 'string') { throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`); } return new TextEncoder().encode(str); } export function toBytes(data) { if (typeof data === 'string') data = utf8ToBytes(data); if (!(data instanceof Uint8Array)) throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`); return data; } /** * Concats Uint8Array-s into one; like `Buffer.concat([buf1, buf2])` * @example concatBytes(buf1, buf2) */ export function concatBytes(...arrays) { if (!arrays.every((a) => a instanceof Uint8Array)) throw new Error('Uint8Array list expected'); if (arrays.length === 1) return arrays[0]; const length = arrays.reduce((a, arr) => a + arr.length, 0); const result = new Uint8Array(length); for (let i = 0, pad = 0; i < arrays.length; i++) { const arr = arrays[i]; result.set(arr, pad); pad += arr.length; } return result; } // For runtime check if class implements interface export class Hash { // Safe version that clones internal state clone() { return this._cloneInto(); } } // Check if object doens't have custom constructor (like Uint8Array/Array) const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object; export function checkOpts(defaults, opts) { if (opts !== undefined && (typeof opts !== 'object' || !isPlainObject(opts))) throw new TypeError('Options should be object or undefined'); const merged = Object.assign(defaults, opts); return merged; } export function wrapConstructor(hashConstructor) { const hashC = (message) => hashConstructor().update(toBytes(message)).digest(); const tmp = hashConstructor(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashConstructor(); return hashC; } export function wrapConstructorWithOpts(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest(); const tmp = hashCons({}); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = (opts) => hashCons(opts); return hashC; } /** * Secure PRNG. Uses `globalThis.crypto` or node.js crypto module. */ export function randomBytes(bytesLength = 32) { if (crypto && typeof crypto.getRandomValues === 'function') { return crypto.getRandomValues(new Uint8Array(bytesLength)); } throw new Error('crypto.getRandomValues must be defined'); }