fixednumber.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. "use strict";
  2. import { arrayify, BytesLike, hexZeroPad, isBytes } from "@ethersproject/bytes";
  3. import { Logger } from "@ethersproject/logger";
  4. import { version } from "./_version";
  5. const logger = new Logger(version);
  6. import { BigNumber, BigNumberish, isBigNumberish } from "./bignumber";
  7. const _constructorGuard = { };
  8. const Zero = BigNumber.from(0);
  9. const NegativeOne = BigNumber.from(-1);
  10. function throwFault(message: string, fault: string, operation: string, value?: any): never {
  11. const params: any = { fault: fault, operation: operation };
  12. if (value !== undefined) { params.value = value; }
  13. return logger.throwError(message, Logger.errors.NUMERIC_FAULT, params);
  14. }
  15. // Constant to pull zeros from for multipliers
  16. let zeros = "0";
  17. while (zeros.length < 256) { zeros += zeros; }
  18. // Returns a string "1" followed by decimal "0"s
  19. function getMultiplier(decimals: BigNumberish): string {
  20. if (typeof(decimals) !== "number") {
  21. try {
  22. decimals = BigNumber.from(decimals).toNumber();
  23. } catch (e) { }
  24. }
  25. if (typeof(decimals) === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) {
  26. return ("1" + zeros.substring(0, decimals));
  27. }
  28. return logger.throwArgumentError("invalid decimal size", "decimals", decimals);
  29. }
  30. export function formatFixed(value: BigNumberish, decimals?: string | BigNumberish): string {
  31. if (decimals == null) { decimals = 0; }
  32. const multiplier = getMultiplier(decimals);
  33. // Make sure wei is a big number (convert as necessary)
  34. value = BigNumber.from(value);
  35. const negative = value.lt(Zero);
  36. if (negative) { value = value.mul(NegativeOne); }
  37. let fraction = value.mod(multiplier).toString();
  38. while (fraction.length < multiplier.length - 1) { fraction = "0" + fraction; }
  39. // Strip training 0
  40. fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
  41. const whole = value.div(multiplier).toString();
  42. if (multiplier.length === 1) {
  43. value = whole;
  44. } else {
  45. value = whole + "." + fraction;
  46. }
  47. if (negative) { value = "-" + value; }
  48. return value;
  49. }
  50. export function parseFixed(value: string, decimals?: BigNumberish): BigNumber {
  51. if (decimals == null) { decimals = 0; }
  52. const multiplier = getMultiplier(decimals);
  53. if (typeof(value) !== "string" || !value.match(/^-?[0-9.]+$/)) {
  54. logger.throwArgumentError("invalid decimal value", "value", value);
  55. }
  56. // Is it negative?
  57. const negative = (value.substring(0, 1) === "-");
  58. if (negative) { value = value.substring(1); }
  59. if (value === ".") {
  60. logger.throwArgumentError("missing value", "value", value);
  61. }
  62. // Split it into a whole and fractional part
  63. const comps = value.split(".");
  64. if (comps.length > 2) {
  65. logger.throwArgumentError("too many decimal points", "value", value);
  66. }
  67. let whole = comps[0], fraction = comps[1];
  68. if (!whole) { whole = "0"; }
  69. if (!fraction) { fraction = "0"; }
  70. // Trim trailing zeros
  71. while (fraction[fraction.length - 1] === "0") {
  72. fraction = fraction.substring(0, fraction.length - 1);
  73. }
  74. // Check the fraction doesn't exceed our decimals size
  75. if (fraction.length > multiplier.length - 1) {
  76. throwFault("fractional component exceeds decimals", "underflow", "parseFixed");
  77. }
  78. // If decimals is 0, we have an empty string for fraction
  79. if (fraction === "") { fraction = "0"; }
  80. // Fully pad the string with zeros to get to wei
  81. while (fraction.length < multiplier.length - 1) { fraction += "0"; }
  82. const wholeValue = BigNumber.from(whole);
  83. const fractionValue = BigNumber.from(fraction);
  84. let wei = (wholeValue.mul(multiplier)).add(fractionValue);
  85. if (negative) { wei = wei.mul(NegativeOne); }
  86. return wei;
  87. }
  88. export class FixedFormat {
  89. readonly signed: boolean;
  90. readonly width: number;
  91. readonly decimals: number;
  92. readonly name: string;
  93. readonly _multiplier: string;
  94. constructor(constructorGuard: any, signed: boolean, width: number, decimals: number) {
  95. if (constructorGuard !== _constructorGuard) {
  96. logger.throwError("cannot use FixedFormat constructor; use FixedFormat.from", Logger.errors.UNSUPPORTED_OPERATION, {
  97. operation: "new FixedFormat"
  98. });
  99. }
  100. this.signed = signed;
  101. this.width = width;
  102. this.decimals = decimals;
  103. this.name = (signed ? "": "u") + "fixed" + String(width) + "x" + String(decimals);
  104. this._multiplier = getMultiplier(decimals);
  105. Object.freeze(this);
  106. }
  107. static from(value: any): FixedFormat {
  108. if (value instanceof FixedFormat) { return value; }
  109. if (typeof(value) === "number") {
  110. value = `fixed128x${value}`
  111. }
  112. let signed = true;
  113. let width = 128;
  114. let decimals = 18;
  115. if (typeof(value) === "string") {
  116. if (value === "fixed") {
  117. // defaults...
  118. } else if (value === "ufixed") {
  119. signed = false;
  120. } else {
  121. const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
  122. if (!match) { logger.throwArgumentError("invalid fixed format", "format", value); }
  123. signed = (match[1] !== "u");
  124. width = parseInt(match[2]);
  125. decimals = parseInt(match[3]);
  126. }
  127. } else if (value) {
  128. const check = (key: string, type: string, defaultValue: any): any => {
  129. if (value[key] == null) { return defaultValue; }
  130. if (typeof(value[key]) !== type) {
  131. logger.throwArgumentError("invalid fixed format (" + key + " not " + type +")", "format." + key, value[key]);
  132. }
  133. return value[key];
  134. }
  135. signed = check("signed", "boolean", signed);
  136. width = check("width", "number", width);
  137. decimals = check("decimals", "number", decimals);
  138. }
  139. if (width % 8) {
  140. logger.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width);
  141. }
  142. if (decimals > 80) {
  143. logger.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals);
  144. }
  145. return new FixedFormat(_constructorGuard, signed, width, decimals);
  146. }
  147. }
  148. export class FixedNumber {
  149. readonly format: FixedFormat;
  150. readonly _hex: string;
  151. readonly _value: string;
  152. readonly _isFixedNumber: boolean;
  153. constructor(constructorGuard: any, hex: string, value: string, format?: FixedFormat) {
  154. logger.checkNew(new.target, FixedNumber);
  155. if (constructorGuard !== _constructorGuard) {
  156. logger.throwError("cannot use FixedNumber constructor; use FixedNumber.from", Logger.errors.UNSUPPORTED_OPERATION, {
  157. operation: "new FixedFormat"
  158. });
  159. }
  160. this.format = format;
  161. this._hex = hex;
  162. this._value = value;
  163. this._isFixedNumber = true;
  164. Object.freeze(this);
  165. }
  166. _checkFormat(other: FixedNumber): void {
  167. if (this.format.name !== other.format.name) {
  168. logger.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other);
  169. }
  170. }
  171. addUnsafe(other: FixedNumber): FixedNumber {
  172. this._checkFormat(other);
  173. const a = parseFixed(this._value, this.format.decimals);
  174. const b = parseFixed(other._value, other.format.decimals);
  175. return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format);
  176. }
  177. subUnsafe(other: FixedNumber): FixedNumber {
  178. this._checkFormat(other);
  179. const a = parseFixed(this._value, this.format.decimals);
  180. const b = parseFixed(other._value, other.format.decimals);
  181. return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format);
  182. }
  183. mulUnsafe(other: FixedNumber): FixedNumber {
  184. this._checkFormat(other);
  185. const a = parseFixed(this._value, this.format.decimals);
  186. const b = parseFixed(other._value, other.format.decimals);
  187. return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format);
  188. }
  189. divUnsafe(other: FixedNumber): FixedNumber {
  190. this._checkFormat(other);
  191. const a = parseFixed(this._value, this.format.decimals);
  192. const b = parseFixed(other._value, other.format.decimals);
  193. return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format);
  194. }
  195. floor(): FixedNumber {
  196. const comps = this.toString().split(".");
  197. if (comps.length === 1) { comps.push("0"); }
  198. let result = FixedNumber.from(comps[0], this.format);
  199. const hasFraction = !comps[1].match(/^(0*)$/);
  200. if (this.isNegative() && hasFraction) {
  201. result = result.subUnsafe(ONE.toFormat(result.format));
  202. }
  203. return result;
  204. }
  205. ceiling(): FixedNumber {
  206. const comps = this.toString().split(".");
  207. if (comps.length === 1) { comps.push("0"); }
  208. let result = FixedNumber.from(comps[0], this.format);
  209. const hasFraction = !comps[1].match(/^(0*)$/);
  210. if (!this.isNegative() && hasFraction) {
  211. result = result.addUnsafe(ONE.toFormat(result.format));
  212. }
  213. return result;
  214. }
  215. // @TODO: Support other rounding algorithms
  216. round(decimals?: number): FixedNumber {
  217. if (decimals == null) { decimals = 0; }
  218. // If we are already in range, we're done
  219. const comps = this.toString().split(".");
  220. if (comps.length === 1) { comps.push("0"); }
  221. if (decimals < 0 || decimals > 80 || (decimals % 1)) {
  222. logger.throwArgumentError("invalid decimal count", "decimals", decimals);
  223. }
  224. if (comps[1].length <= decimals) { return this; }
  225. const factor = FixedNumber.from("1" + zeros.substring(0, decimals), this.format);
  226. const bump = BUMP.toFormat(this.format);
  227. return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor);
  228. }
  229. isZero(): boolean {
  230. return (this._value === "0.0" || this._value === "0");
  231. }
  232. isNegative(): boolean {
  233. return (this._value[0] === "-");
  234. }
  235. toString(): string { return this._value; }
  236. toHexString(width?: number): string {
  237. if (width == null) { return this._hex; }
  238. if (width % 8) { logger.throwArgumentError("invalid byte width", "width", width); }
  239. const hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString();
  240. return hexZeroPad(hex, width / 8);
  241. }
  242. toUnsafeFloat(): number { return parseFloat(this.toString()); }
  243. toFormat(format: FixedFormat | string): FixedNumber {
  244. return FixedNumber.fromString(this._value, format);
  245. }
  246. static fromValue(value: BigNumber, decimals?: BigNumberish, format?: FixedFormat | string | number): FixedNumber {
  247. // If decimals looks more like a format, and there is no format, shift the parameters
  248. if (format == null && decimals != null && !isBigNumberish(decimals)) {
  249. format = decimals;
  250. decimals = null;
  251. }
  252. if (decimals == null) { decimals = 0; }
  253. if (format == null) { format = "fixed"; }
  254. return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format));
  255. }
  256. static fromString(value: string, format?: FixedFormat | string | number): FixedNumber {
  257. if (format == null) { format = "fixed"; }
  258. const fixedFormat = FixedFormat.from(format);
  259. const numeric = parseFixed(value, fixedFormat.decimals);
  260. if (!fixedFormat.signed && numeric.lt(Zero)) {
  261. throwFault("unsigned value cannot be negative", "overflow", "value", value);
  262. }
  263. let hex: string = null;
  264. if (fixedFormat.signed) {
  265. hex = numeric.toTwos(fixedFormat.width).toHexString();
  266. } else {
  267. hex = numeric.toHexString();
  268. hex = hexZeroPad(hex, fixedFormat.width / 8);
  269. }
  270. const decimal = formatFixed(numeric, fixedFormat.decimals);
  271. return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
  272. }
  273. static fromBytes(value: BytesLike, format?: FixedFormat | string | number): FixedNumber {
  274. if (format == null) { format = "fixed"; }
  275. const fixedFormat = FixedFormat.from(format);
  276. if (arrayify(value).length > fixedFormat.width / 8) {
  277. throw new Error("overflow");
  278. }
  279. let numeric = BigNumber.from(value);
  280. if (fixedFormat.signed) { numeric = numeric.fromTwos(fixedFormat.width); }
  281. const hex = numeric.toTwos((fixedFormat.signed ? 0: 1) + fixedFormat.width).toHexString();
  282. const decimal = formatFixed(numeric, fixedFormat.decimals);
  283. return new FixedNumber(_constructorGuard, hex, decimal, fixedFormat);
  284. }
  285. static from(value: any, format?: FixedFormat | string | number) {
  286. if (typeof(value) === "string") {
  287. return FixedNumber.fromString(value, format);
  288. }
  289. if (isBytes(value)) {
  290. return FixedNumber.fromBytes(value, format);
  291. }
  292. try {
  293. return FixedNumber.fromValue(value, 0, format);
  294. } catch (error) {
  295. // Allow NUMERIC_FAULT to bubble up
  296. if (error.code !== Logger.errors.INVALID_ARGUMENT) {
  297. throw error;
  298. }
  299. }
  300. return logger.throwArgumentError("invalid FixedNumber value", "value", value);
  301. }
  302. static isFixedNumber(value: any): value is FixedNumber {
  303. return !!(value && value._isFixedNumber);
  304. }
  305. }
  306. const ONE = FixedNumber.from(1);
  307. const BUMP = FixedNumber.from("0.5");