UNPKG

@mimicry/sdk

Version:

A node SDK designed to simplify interaction with the Mimicry Protocol smart contracts.

1,841 lines (1,832 loc) 80.9 kB
import { Contract, isAddress } from 'ethers'; import { batchTicksToCandle } from 'candlestick-convert'; import { Decimal } from 'decimal.js'; function _regeneratorRuntime() { _regeneratorRuntime = function () { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function (obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function (method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function (skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function () { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function (exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function (type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function (record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function (finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function (tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function (iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var ChainId; (function (ChainId) { ChainId[ChainId["POLYGON_POS"] = 137] = "POLYGON_POS"; ChainId[ChainId["POLYGON_MUMBAI"] = 80001] = "POLYGON_MUMBAI"; })(ChainId || (ChainId = {})); var CurrencySymbol; (function (CurrencySymbol) { CurrencySymbol["USD"] = "usd"; CurrencySymbol["WETH"] = "weth"; CurrencySymbol["USDC"] = "usdc"; CurrencySymbol["MATIC"] = "matic"; })(CurrencySymbol || (CurrencySymbol = {})); var Direction; (function (Direction) { Direction[Direction["SHORT"] = 0] = "SHORT"; Direction[Direction["LONG"] = 1] = "LONG"; })(Direction || (Direction = {})); var MetricType; (function (MetricType) { MetricType["MARKET_CAP"] = "marketcap"; })(MetricType || (MetricType = {})); var OracleType; (function (OracleType) { OracleType["OMO"] = "open-markets-oracle"; })(OracleType || (OracleType = {})); var Timeframe; (function (Timeframe) { Timeframe[Timeframe["ONE_MINUTE"] = 60] = "ONE_MINUTE"; Timeframe[Timeframe["FIVE_MINUTES"] = 300] = "FIVE_MINUTES"; Timeframe[Timeframe["FIFTEEN_MINUTES"] = 900] = "FIFTEEN_MINUTES"; Timeframe[Timeframe["THIRTY_MINUTES"] = 1800] = "THIRTY_MINUTES"; Timeframe[Timeframe["ONE_HOUR"] = 3600] = "ONE_HOUR"; Timeframe[Timeframe["FOUR_HOURS"] = 14400] = "FOUR_HOURS"; Timeframe[Timeframe["ONE_DAY"] = 86400] = "ONE_DAY"; Timeframe[Timeframe["ONE_WEEK"] = 604800] = "ONE_WEEK"; })(Timeframe || (Timeframe = {})); // export enum TransferType { // DEPOSIT = 'deposit', // WITHDRAW = 'withdraw', // FEE_PAYMENT = 'fee-payment', // FEE_CREDIT = 'fee-credit', // REWARD = 'token-reward', // } /** * Given a BigInt, return an Value object with a CurrencyInfo and Amount. */ function numberToBigInt(_value, _currencyInfo) { // Convert the value to a BigInt based on the decimals of the currency. var decimals = Number(_currencyInfo.decimals); var atomic = BigInt(_value * Math.pow(10, decimals)); return atomic; } var Currency = /*#__PURE__*/function () { function Currency(_contract) { this.contract = _contract; } Currency.initialize = /*#__PURE__*/function () { var _initialize = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_address, _signer) { var abi, contract; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (process.env.NODE_ENV !== "production") { console.log("Initialize Currency: " + _address); } abi = ['function name() view returns (string)', 'function symbol() view returns (string)', 'function decimals() view returns (uint8)', 'function approve(address spender, uint256 amount) returns (bool)']; contract = new Contract(_address, abi, _signer); return _context.abrupt("return", new Currency(contract)); case 4: case "end": return _context.stop(); } }, _callee); })); function initialize(_x, _x2) { return _initialize.apply(this, arguments); } return initialize; }(); var _proto = Currency.prototype; _proto.getInfo = /*#__PURE__*/function () { var _getInfo = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { var info; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: if (!this.info) { _context2.next = 2; break; } return _context2.abrupt("return", this.info); case 2: _context2.next = 4; return this.contract.name(); case 4: _context2.t0 = _context2.sent; _context2.next = 7; return this.contract.symbol(); case 7: _context2.t1 = _context2.sent; _context2.next = 10; return this.contract.decimals(); case 10: _context2.t2 = _context2.sent; _context2.next = 13; return this.contract.getAddress(); case 13: _context2.t3 = _context2.sent; info = { name: _context2.t0, symbol: _context2.t1, decimals: _context2.t2, address: _context2.t3 }; this.info = info; return _context2.abrupt("return", info); case 17: case "end": return _context2.stop(); } }, _callee2, this); })); function getInfo() { return _getInfo.apply(this, arguments); } return getInfo; }() /** * Approve Spending * * @param _spender The address of the market contract * @param _amount The amount as a human-readable decimal * @returns The transaction response */ ; _proto.approveSpending = /*#__PURE__*/ function () { var _approveSpending = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_spender, _amount) { var amount, tx; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.t0 = numberToBigInt; _context3.t1 = _amount; _context3.next = 4; return this.getInfo(); case 4: _context3.t2 = _context3.sent; amount = (0, _context3.t0)(_context3.t1, _context3.t2); _context3.next = 8; return this.contract.approve(_spender, amount); case 8: tx = _context3.sent; _context3.next = 11; return tx.wait(); case 11: return _context3.abrupt("return", _context3.sent); case 12: case "end": return _context3.stop(); } }, _callee3, this); })); function approveSpending(_x3, _x4) { return _approveSpending.apply(this, arguments); } return approveSpending; }(); return Currency; }(); var Oracle = /*#__PURE__*/function () { function Oracle(_contract, _metadata) { this.validate(_metadata); this.contract = _contract; this.metadata = _metadata; } var _proto = Oracle.prototype; _proto.getTicks = /*#__PURE__*/function () { var _getTicks = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: throw new Error('getTicks() method not implemented.'); case 1: case "end": return _context.stop(); } }, _callee); })); function getTicks() { return _getTicks.apply(this, arguments); } return getTicks; }(); _proto.getOHLCV = /*#__PURE__*/function () { var _getOHLCV = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_timeframe) { return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: throw new Error('getOHLCV() method not implemented.'); case 1: case "end": return _context2.stop(); } }, _callee2); })); function getOHLCV(_x) { return _getOHLCV.apply(this, arguments); } return getOHLCV; }(); _proto.getOHLCVFromTicks = function getOHLCVFromTicks(_ticks, _timeframe) { if (process.env.NODE_ENV !== "production") { console.log("Oracle.getOHLCVFromTicks(" + _timeframe + ")"); } var candles = batchTicksToCandle(_ticks, 60, true); return candles; }; _proto.getContract = function getContract() { return this.contract; }; _proto.getMetadata = function getMetadata() { return this.metadata; }; _proto.getTick = function getTick(_time, _price, _quantity) { if (!_quantity) { _quantity = BigInt(0); } return { time: Number(_time), price: Number(_price), quantity: Number(_quantity) }; }; _proto.validate = function validate(_metadata) { if (!Object.values(OracleType).includes(_metadata.type)) { throw new Error('metadata.type must be a valid OracleType'); } if (!isAddress(_metadata.address)) { throw new Error('metadata.address must be a valid address'); } if (process.env.NODE_ENV !== "production") { console.log("Oracle.validate() passed."); } }; return Oracle; }(); var OpenMarketsOracle = /*#__PURE__*/function (_Oracle) { _inheritsLoose(OpenMarketsOracle, _Oracle); function OpenMarketsOracle(_contract, _metadata) { var _this; _this = _Oracle.call(this, _contract, _metadata) || this; _this.dataFeedId = _metadata.dataFeedId; return _this; } OpenMarketsOracle.initialize = /*#__PURE__*/function () { var _initialize = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_metadata, _signer) { var abi, contract; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (process.env.NODE_ENV !== "production") { console.log("Initialize OpenMarketsOracle with metadata:"); console.log(_metadata); } abi = ['function getValues(uint256 dataFeedId, uint256 limit, uint256 offset) view returns ((uint256, uint256)[])', 'function getLatestValue(uint256 dataFeedId) view returns (uint256, uint256)']; contract = new Contract(_metadata.address, abi, _signer); return _context.abrupt("return", new OpenMarketsOracle(contract, _metadata)); case 4: case "end": return _context.stop(); } }, _callee); })); function initialize(_x, _x2) { return _initialize.apply(this, arguments); } return initialize; }(); var _proto = OpenMarketsOracle.prototype; _proto.getLatestValue = /*#__PURE__*/function () { var _getLatestValue = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.getContract().getLatestValue(this.dataFeedId); case 2: return _context2.abrupt("return", _context2.sent); case 3: case "end": return _context2.stop(); } }, _callee2, this); })); function getLatestValue() { return _getLatestValue.apply(this, arguments); } return getLatestValue; }(); _proto.getOHLCV = /*#__PURE__*/function () { var _getOHLCV = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_timeframe) { var ticks; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.getTicks(); case 2: ticks = _context3.sent; _context3.next = 5; return this.getOHLCVFromTicks(ticks, _timeframe); case 5: return _context3.abrupt("return", _context3.sent); case 6: case "end": return _context3.stop(); } }, _callee3, this); })); function getOHLCV(_x3) { return _getOHLCV.apply(this, arguments); } return getOHLCV; }(); _proto.getTicks = /*#__PURE__*/function () { var _getTicks = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { var _this2 = this; var offset, limit, ticks, done, values; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: offset = 0; limit = 1000; ticks = []; done = false; case 4: if (done) { _context4.next = 14; break; } _context4.next = 7; return this.getContract().getValues(this.dataFeedId, limit, offset); case 7: values = _context4.sent; if (values.length < limit || values.length === 0) { done = true; } ticks = ticks.concat(values.map(function (v) { return _this2.getTick(v[1], v[0]); })); offset += limit; if (process.env.NODE_ENV !== "production") { console.log("Offset: " + offset); } _context4.next = 4; break; case 14: return _context4.abrupt("return", ticks); case 15: case "end": return _context4.stop(); } }, _callee4, this); })); function getTicks() { return _getTicks.apply(this, arguments); } return getTicks; }(); _proto.validate = function validate(_metadata) { _Oracle.prototype.validate.call(this, _metadata); if (_metadata.type !== OracleType.OMO) { throw new Error('metadata.type must be "open-markets-oracle"'); } if (_metadata.dataFeedId < 1) { throw new Error('Must provide a valid dataFeedId for the oracle'); } if (process.env.NODE_ENV !== "production") { console.log("OpenMarketsOracle.validate() passed."); } }; return OpenMarketsOracle; }(Oracle); /** * Given a BigInt, return an Value object with a CurrencyInfo and Amount. */ function bigIntToValue(value, currencyInfo) { var decimals = Number(currencyInfo.decimals); var decimal = new Decimal(Number(value) / Math.pow(10, decimals)); var atomic = value; return { currency: currencyInfo, amount: { atomic: atomic, decimal: decimal } }; } var abi = [ { inputs: [ ], stateMutability: "nonpayable", type: "constructor" }, { inputs: [ ], name: "InsufficientOpeningValue", type: "error" }, { inputs: [ ], name: "InvalidAdjustmentAmount", type: "error" }, { inputs: [ ], name: "InvalidSender", type: "error" }, { inputs: [ ], name: "InvalidTokenId", type: "error" }, { inputs: [ ], name: "NativeTokenIncorrectAmount", type: "error" }, { inputs: [ ], name: "NativeTokenTransferFailed", type: "error" }, { inputs: [ ], name: "OnlyAccountant", type: "error" }, { inputs: [ ], name: "PositionEditDurationLimit", type: "error" }, { inputs: [ ], name: "PositionIsLiquidated", type: "error" }, { inputs: [ ], name: "UnsupportedCurrency", type: "error" }, { anonymous: false, inputs: [ { indexed: false, internalType: "address", name: "previousAdmin", type: "address" }, { indexed: false, internalType: "address", name: "newAdmin", type: "address" } ], name: "AdminChanged", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "address", name: "beacon", type: "address" } ], name: "BeaconUpgraded", type: "event" }, { anonymous: false, inputs: [ { indexed: false, internalType: "uint8", name: "version", type: "uint8" } ], name: "Initialized", type: "event" }, { anonymous: false, inputs: [ { indexed: false, internalType: "address", name: "valueProvider", type: "address" }, { indexed: false, internalType: "address", name: "accountantAddress", type: "address" }, { indexed: false, internalType: "string", name: "metadataURI", type: "string" } ], name: "MarketInitialized", type: "event" }, { anonymous: false, inputs: [ { indexed: false, internalType: "string", name: "newMetadataURI", type: "string" } ], name: "MetadataURIUpdated", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "address", name: "previousOwner", type: "address" }, { indexed: true, internalType: "address", name: "newOwner", type: "address" } ], name: "OwnershipTransferred", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "uint256", name: "tokenId", type: "uint256" }, { indexed: true, internalType: "address", name: "owner", type: "address" }, { indexed: false, internalType: "enum Direction", name: "direction", type: "uint8" }, { indexed: false, internalType: "uint256", name: "closingUsdValue", type: "uint256" }, { indexed: false, internalType: "uint256", name: "closingSpotPrice", type: "uint256" }, { indexed: false, internalType: "bool", name: "isLiquidated", type: "bool" } ], name: "PositionClosed", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "uint256", name: "tokenId", type: "uint256" }, { indexed: true, internalType: "address", name: "owner", type: "address" }, { indexed: false, internalType: "enum Direction", name: "direction", type: "uint8" }, { indexed: false, internalType: "address", name: "currency", type: "address" }, { indexed: false, internalType: "uint256", name: "openingTokenAmount", type: "uint256" }, { indexed: false, internalType: "uint256", name: "openingUsdValue", type: "uint256" }, { indexed: false, internalType: "uint256", name: "openingSpotPrice", type: "uint256" }, { indexed: false, internalType: "uint256", name: "multiplier", type: "uint256" } ], name: "PositionOpened", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "uint256", name: "tokenId", type: "uint256" }, { indexed: false, internalType: "int256", name: "adjustmentAmountUsd", type: "int256" } ], name: "PositionUpdated", type: "event" }, { anonymous: false, inputs: [ { indexed: true, internalType: "address", name: "implementation", type: "address" } ], name: "Upgraded", type: "event" }, { inputs: [ { internalType: "address", name: "_currency", type: "address" }, { internalType: "address", name: "_recipient", type: "address" }, { internalType: "uint256", name: "_value", type: "uint256" }, { internalType: "uint256", name: "_fee", type: "uint256" } ], name: "_handlePayout", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ ], name: "accountant", outputs: [ { internalType: "contract Accountant", name: "", type: "address" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "address", name: "from", type: "address" }, { internalType: "uint256[]", name: "positionIds", type: "uint256[]" } ], name: "batchClosePositions", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ ], name: "calculatePositionValues", outputs: [ { internalType: "uint256", name: "longsValue", type: "uint256" }, { internalType: "uint256", name: "shortsValue", type: "uint256" }, { internalType: "uint256", name: "transferAmount", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "uint256", name: "_tokenId", type: "uint256" } ], name: "closePosition", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ ], name: "commitValueTransfer", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ ], name: "feeDividend", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "enum Direction", name: "_direction", type: "uint8" }, { internalType: "address", name: "_tokenAddress", type: "address" } ], name: "getCurrencyPoolUSDValue", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "enum Direction", name: "_direction", type: "uint8" } ], name: "getDirectionUSDValue", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ ], name: "getIndexValue", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "enum Direction", name: "_direction", type: "uint8" } ], name: "getLastLiquidationTimestamp", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "uint256", name: "_tokenId", type: "uint256" } ], name: "getPositionValue", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "uint256", name: "_tokenId", type: "uint256" }, { internalType: "uint256", name: "_amount", type: "uint256" } ], name: "increasePosition", outputs: [ ], stateMutability: "payable", type: "function" }, { inputs: [ { internalType: "contract IValueProvider", name: "_valueProvider", type: "address" }, { internalType: "contract IMimicry", name: "_mimicryAddress", type: "address" }, { internalType: "contract Accountant", name: "_accountantAddress", type: "address" }, { internalType: "contract IERC721Upgradeable", name: "_positionToken", type: "address" }, { internalType: "string", name: "_name", type: "string" }, { internalType: "string", name: "_metadataURI", type: "string" } ], name: "initialize", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "uint256", name: "_tokenId", type: "uint256" } ], name: "isPositionEditable", outputs: [ { internalType: "bool", name: "", type: "bool" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "uint256", name: "_tokenId", type: "uint256" } ], name: "isPositionLiquidated", outputs: [ { internalType: "bool", name: "", type: "bool" } ], stateMutability: "view", type: "function" }, { inputs: [ ], name: "metadataURI", outputs: [ { internalType: "string", name: "", type: "string" } ], stateMutability: "view", type: "function" }, { inputs: [ ], name: "mimicry", outputs: [ { internalType: "contract IMimicry", name: "", type: "address" } ], stateMutability: "view", type: "function" }, { inputs: [ ], name: "minPositionEditDuration", outputs: [ { internalType: "uint256", name: "", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ ], name: "name", outputs: [ { internalType: "string", name: "", type: "string" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "enum Direction", name: "_direction", type: "uint8" }, { internalType: "address", name: "_tokenAddress", type: "address" }, { internalType: "uint256", name: "_openingValue", type: "uint256" } ], name: "openPosition", outputs: [ ], stateMutability: "payable", type: "function" }, { inputs: [ ], name: "owner", outputs: [ { internalType: "address", name: "", type: "address" } ], stateMutability: "view", type: "function" }, { inputs: [ ], name: "positionToken", outputs: [ { internalType: "contract IERC721Upgradeable", name: "", type: "address" } ], stateMutability: "view", type: "function" }, { inputs: [ { internalType: "uint256", name: "", type: "uint256" } ], name: "positionsMap", outputs: [ { internalType: "enum Direction", name: "direction", type: "uint8" }, { internalType: "address", name: "currency", type: "address" }, { internalType: "uint256", name: "multiplier", type: "uint256" }, { internalType: "uint256", name: "tokenId", type: "uint256" }, { internalType: "uint256", name: "createdAt", type: "uint256" }, { internalType: "uint256", name: "editedAt", type: "uint256" } ], stateMutability: "view", type: "function" }, { inputs: [ ], name: "proxiableUUID", outputs: [ { internalType: "bytes32", name: "", type: "bytes32" } ], stateMutability: "view", type: "function" }, { inputs: [ ], name: "renounceOwnership", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "string", name: "_metadataURI", type: "string" } ], name: "setMetadataURI", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "newOwner", type: "address" } ], name: "transferOwnership", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "newImplementation", type: "address" } ], name: "upgradeTo", outputs: [ ], stateMutability: "nonpayable", type: "function" }, { inputs: [ { internalType: "address", name: "newImplementation", type: "address" }, { internalType: "bytes", name: "data", type: "bytes" } ], name: "upgradeToAndCall", outputs: [ ], stateMutability: "payable", type: "function" }, { inputs: [ ], name: "valueProvider", outputs: [ { internalType: "contract IValueProvider", name: "", type: "address" } ], stateMutability: "view", type: "function" } ]; var Market = /*#__PURE__*/function () { function Market(_contract, _signer) { this.contract = _contract; this.signer = _signer; } Market.initialize = /*#__PURE__*/function () { var _initialize = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(_address, _signer) { var contract; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: if (process.env.NODE_ENV !== "production") { console.log("Initialize Market: " + _address); } contract = new Contract(_address, abi, _signer); return _context.abrupt("return", new Market(contract, _signer)); case 3: case "end": return _context.stop(); } }, _callee); })); function initialize(_x, _x2) { return _initialize.apply(this, arguments); } return initialize; }() // ---- MARKET INFO --------------------------------------------------------- ; var _proto = Market.prototype; _proto.getInfo = /*#__PURE__*/ function () { var _getInfo = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() { var metadata, currencyInfo, info; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.getMetadata(); case 2: metadata = _context2.sent; _context2.next = 5; return this.getCurrencyInfo(metadata.currency); case 5: currencyInfo = _context2.sent; _context2.t0 = metadata.name; _context2.next = 9; return this.getAddress(); case 9: _context2.t1 = _context2.sent; _context2.t2 = metadata.description; _context2.t3 = metadata.image; _context2.t4 = metadata.metric; _context2.next = 15; return this.getReferenceValue(currencyInfo); case 15: _context2.t5 = _context2.sent; _context2.next = 18; return this.getSkew(); case 18: _context2.t6 = _context2.sent; info = { name: _context2.t0, address: _context2.t1, description: _context2.t2, image: _context2.t3, metric: _context2.t4, referenceValue: _context2.t5, skew: _context2.t6 }; return _context2.abrupt("return", info); case 21: case "end": return _context2.stop(); } }, _callee2, this); })); function getInfo() { return _getInfo.apply(this, arguments); } return getInfo; }(); _proto.getMetadata = /*#__PURE__*/function () { var _getMetadata = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(force) { var url, response, json; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: if (force === void 0) { force = false; } if (!(this.metadata && !force)) { _context3.next = 3; break; } return _context3.abrupt("return", this.metadata); case 3: _context3.next = 5; return this.contract.metadataURI(); case 5: url = _context3.sent; if (process.env.NODE_ENV !== "production") { console.log("Market Metadata URL: " + url); } _context3.next = 9; return fetch(url); case 9: response = _context3.sent; _context3.next = 12; return response.json(); case 12: json = _context3.sent; this.metadata = json; return _context3.abrupt("return", json); case 15: case "end": return _context3.stop(); } }, _callee3, this); })); function getMetadata(_x3) { return _getMetadata.apply(this, arguments); } return getMetadata; }(); _proto.getAddress = /*#__PURE__*/function () { var _getAddress = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() { return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return this.contract.getAddress(); case 2: return _context4.abrupt("return", _context4.sent); case 3: case "end": return _context4.stop(); } }, _callee4, this); })); function getAddress() { return _getAddress.apply(this, arguments); } return getAddress; }(); _proto.getSkew = /*#__PURE__*/function () { var _getSkew = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() { var positionValues, currencyInfo, _long, _short; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: _context5.next = 2; return this.contract.calculatePositionValues(); case 2: positionValues = _context5.sent; _context5.next = 5; return this.getCurrencyInfo(CurrencySymbol.USD); case 5: currencyInfo = _context5.sent; _long = bigIntToValue(positionValues[0], currencyInfo); _short = bigIntToValue(positionValues[1], currencyInfo); return _context5.abrupt("return", { currency: currencyInfo, "long": _long.amount, "short": _short.amount }); case 9: case "end": return _context5.stop(); } }, _callee5, this); })); function getSkew() { return _getSkew.apply(this, arguments); } return getSkew; }() // ---- ORACLE -------------------------------------------------------------- ; _proto.getReferenceValue = /*#__PURE__*/ function () { var _getReferenceValue = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_currencyInfo) { return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: _context6.t0 = bigIntToValue; _context6.next = 3; return this.contract.getIndexValue(); case 3: _context6.t1 = _context6.sent; _context6.