UNPKG

raiden-ts

Version:

Raiden Light Client Typescript/Javascript SDK

226 lines 9.3 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.templateLiteral = exports.bnMax = exports.last = exports.instanceOf = exports.Signed = exports.untime = exports.timed = exports.Timed = exports.Address = exports.PublicKey = exports.PrivateKey = exports.Secret = exports.Hash = exports.Signature = exports.UInt = exports.Int = exports.HexString = exports.BigNumberC = exports.isntNil = exports.decode = void 0; /* eslint-disable @typescript-eslint/no-explicit-any */ const address_1 = require("@ethersproject/address"); const bignumber_1 = require("@ethersproject/bignumber"); const bytes_1 = require("@ethersproject/bytes"); const constants_1 = require("@ethersproject/constants"); const Either_1 = require("fp-ts/lib/Either"); const t = __importStar(require("io-ts")); const PathReporter_1 = require("io-ts/lib/PathReporter"); const memoize_1 = __importDefault(require("lodash/memoize")); const error_1 = require("./error"); function reporterAssert(value) { if ((0, Either_1.isLeft)(value)) { throw new Error(PathReporter_1.PathReporter.report(value).join('\n')); } } /** * Decode/validate like codec.decode, but throw or return right instead of Either * * @param codec - io-ts codec to be used for decoding/validation * @param data - data to decode/validate * @param customError - Message or error to throw if the decoding fails * @param log - Logger to log error to * @returns Decoded value of codec type */ function decode(codec, data, customError, log) { try { const decoded = codec.decode(data); reporterAssert(decoded); return decoded.right; } catch (originalError) { log?.('__decode failed:', codec.name, codec, data, originalError); throw customError ? customError instanceof Error ? Object.assign(customError, { data }) : new error_1.RaidenError(customError, { data }) : Object.assign(originalError, { data }); } } exports.decode = decode; /** * Test for value's non-nulliness * Like lodash's negate(isNil), but also works as type guard (e.g. useful for filters) * * @param value - to be tested * @returns true if value is not null nor undefined */ function isntNil(value) { return value != null; } exports.isntNil = isntNil; exports.BigNumberC = new t.Type('BigNumber', bignumber_1.BigNumber.isBigNumber, (u, c) => { try { // BigNumber.from is able to decode number, strings and JSON.parse'd {_hex:<str>} objects return t.success(bignumber_1.BigNumber.from(u)); } catch (err) { return t.failure(u, c); } }, (a) => a.toString()); /** * Helper function to create codecs to validate an arbitrary or variable-sized hex bytestring * A branded codec to indicate validated hex-strings * * @param size - Required number of bytes. Pass undefined or zero to have a variable-sized type * @returns branded codec for hex-encoded bytestrings */ exports.HexString = (0, memoize_1.default)(function (size) { return t.brand(t.string, (n) => typeof n === 'string' && (size ? (0, bytes_1.hexDataLength)(n) === size : (0, bytes_1.isHexString)(n)), 'HexString'); }); /** * Helper function to create codecs to validate an arbitrary or variable-sized BigNumbers * A branded codec/type to indicate size-validated BigNumbers * * @param size - Required number of bytes. Pass undefined to have a variable-sized type * @returns branded codec for hex-encoded bytestrings */ exports.Int = (0, memoize_1.default)(function (size) { const min = size ? constants_1.Zero.sub(constants_1.Two.pow(size * 8 - 1)) : undefined, max = size ? constants_1.Two.pow(size * 8 - 1) : undefined; return t.brand(exports.BigNumberC, (n) => exports.BigNumberC.is(n) && (!min || !max || (n.gte(min) && n.lt(max))), 'Int'); }); /** * Helper function to create codecs to validate an arbitrary or variable-sized BigNumbers * A branded codec/type to indicate size-validated BigNumbers * * @param size - Required number of bytes. Pass undefined to have a variable-sized type * @returns branded codec for hex-encoded bytestrings */ exports.UInt = (0, memoize_1.default)(function (size) { const min = size ? constants_1.Zero : undefined, max = size ? constants_1.Two.pow(size * 8) : undefined; return t.brand(exports.BigNumberC, (n) => exports.BigNumberC.is(n) && (!min || !max || (n.gte(min) && n.lt(max))), 'UInt'); }); // specific types // strig brand: ECDSA signature as an hex-string exports.Signature = (0, exports.HexString)(65); // string brand: 256-bit hash, usually keccak256 or sha256 exports.Hash = (0, exports.HexString)(32); // string brand: a secret bytearray, 32 bytes exports.Secret = (0, exports.HexString)(32); // string brand: ECDSA private key, 32 bytes exports.PrivateKey = (0, exports.HexString)(32); // uncompressed secp256k1 public key exports.PublicKey = (0, exports.HexString)(65); function isAddress(u) { try { return (0, address_1.getAddress)(u) === u; } catch (e) { return false; } } exports.Address = new t.RefinementType('Address', isAddress, (u, c) => { try { return t.success((0, address_1.getAddress)(u)); } catch (e) { return t.failure(u, c); } }, t.identity, (0, exports.HexString)(20), isAddress); /** * Helper function to create codecs to validate derived types containing a timestamp ts * * @param codec - Codec to compose with a ts timestamp property * @returns Codec validating such subtype */ exports.Timed = (0, memoize_1.default)((codec) => t.intersection([codec, t.readonly(t.type({ ts: t.number }))])); /** * Given a value of type T, returns a Timed<T> with current time as 'ts' member * * @param v - Value to return with time * @param ts - Timestamp to use, defaults to now * @returns copy of v added of a ts numeric timestamp */ function timed(v, ts = Date.now()) { return { ...v, ts }; } exports.timed = timed; /** * Remove ts timestamp field (from timed) from object passed as parameter (immutably) * * @param v - Timed object * @returns return a copy of v without ts property */ function untime(v) { const { ts: _, ...withoutTs } = v; return withoutTs; } exports.untime = untime; exports.Signed = (0, memoize_1.default)((codec) => t.intersection([codec, t.readonly(t.type({ signature: exports.Signature }))])); /** * Memoized factory to create codecs validating an arbitrary class C * * @param name - Class to create a codec for * @returns Codec validating class C */ exports.instanceOf = (0, memoize_1.default)((name) => new t.Type(`instanceOf(${name})`, (v) => v?.constructor?.name === name, (i, c) => (i?.constructor?.name === name ? t.success(i) : t.failure(i, c)), t.identity)); /** * Like lodash's last, but properly infer return type when argument is a tuple * * @param arr - Tuple or array to get last element from * @returns Last element from arr */ function last(arr) { return arr[arr.length - 1]; } exports.last = last; /** * Math.max for BigNumbers * * @param args - Parameters to compare, must have at least one element * @returns Maxium of parameters as per BigNumber's lt comparison */ function bnMax(...args) { return args.reduce((a, b) => (a.lt(b) ? b : a)); } exports.bnMax = bnMax; /** * Creates a refinement of t.string which validates a template literal string * * @param regex - Regex which matches the generic parameter L * @param name - codec name * @returns refinement type of string to tempalte literal */ function templateLiteral(regex, name) { const regex_ = typeof regex === 'string' ? new RegExp(regex) : regex; const predicate = (u) => regex_.test(u); return new t.RefinementType(name ?? `TemplateLiteral<${regex_.source}>`, (u) => t.string.is(u) && predicate(u), (i, c) => { const e = t.string.validate(i, c); if ((0, Either_1.isLeft)(e)) { return e; } const a = e.right; return predicate(a) ? t.success(a) : t.failure(a, c); }, t.string.encode, t.string, predicate); } exports.templateLiteral = templateLiteral; //# sourceMappingURL=types.js.map