UNPKG

@algofi/js-sdk

Version:

The official Algofi JavaScript SDK

1,484 lines (1,262 loc) 472 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var algosdk = require('algosdk'); var algosdk__default = _interopDefault(algosdk); var request = _interopDefault(require('superagent')); var Base64Encoder = { _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", /** * Function to encode an arbitrary string * * @param string e String to be encoded * @return string t Encoded string e */ encode: function encode(e) { var t = ""; var n, r, i, s, o, u, a; var f = 0; e = Base64Encoder._utf8_encode(e); while (f < e.length) { n = e.charCodeAt(f++); r = e.charCodeAt(f++); i = e.charCodeAt(f++); s = n >> 2; o = (n & 3) << 4 | r >> 4; u = (r & 15) << 2 | i >> 6; a = i & 63; if (isNaN(r)) { u = a = 64; } else if (isNaN(i)) { a = 64; } t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a); } return t; }, /** * Function to decode a string encoded by Base64Encoder.encode * * @param string e String to be decoded * @return string t Decoded string e */ decode: function decode(e) { var t = ""; var n, r, i; var s, o, u, a; var f = 0; e = e.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (f < e.length) { s = this._keyStr.indexOf(e.charAt(f++)); o = this._keyStr.indexOf(e.charAt(f++)); u = this._keyStr.indexOf(e.charAt(f++)); a = this._keyStr.indexOf(e.charAt(f++)); n = s << 2 | o >> 4; r = (o & 15) << 4 | u >> 2; i = (u & 3) << 6 | a; t = t + String.fromCharCode(n); if (u != 64) { t = t + String.fromCharCode(r); } if (a != 64) { t = t + String.fromCharCode(i); } } t = Base64Encoder._utf8_decode(t); return t; }, /** * Function to perfom utf8 encoding on an arbitrary string * * @param string e String to be utf8 encoded * @return string t Encoded string e */ _utf8_encode: function _utf8_encode(e) { e = e.replace(/\r\n/g, "\n"); var t = ""; for (var n = 0; n < e.length; n++) { var r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); } else if (r > 127 && r < 2048) { t += String.fromCharCode(r >> 6 | 192); t += String.fromCharCode(r & 63 | 128); } else { t += String.fromCharCode(r >> 12 | 224); t += String.fromCharCode(r >> 6 & 63 | 128); t += String.fromCharCode(r & 63 | 128); } } return t; }, /** * Function to decode a string encoded by Base64Encoder._utf8_encode * * @param string e String to be utf8 decoded * @return string t Decoded string e */ _utf8_decode: function _utf8_decode(e) { var t = ""; var n = 0; var r = 0; var c2 = 0; var c3 = 0; while (n < e.length) { r = e.charCodeAt(n); if (r < 128) { t += String.fromCharCode(r); n++; } else if (r > 191 && r < 224) { c2 = e.charCodeAt(n + 1); t += String.fromCharCode((r & 31) << 6 | c2 & 63); n += 2; } else { c2 = e.charCodeAt(n + 1); c3 = e.charCodeAt(n + 2); t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63); n += 3; } } return t; } }; // external imports var FIXED_3_SCALE_FACTOR = 1000; var FIXED_6_SCALE_FACTOR = 1000000; var FIXED_12_SCALE_FACTOR = 1000000000000; var FIXED_18_SCALE_FACTOR = /*#__PURE__*/BigInt(1000000000000000000); var ALGO_ASSET_ID = 1; var BANK_ASSET_ID = 900652777; var SECONDS_PER_DAY = 86400; var SECONDS_PER_YEAR = SECONDS_PER_DAY * 365; // requires NoOp, ApplicationCall, No Rekey, No CloseRemainderTo (assits ledger users) var PERMISSIONLESS_SENDER_LOGIC_SIG = /*#__PURE__*/new algosdk.LogicSigAccount( /*#__PURE__*/new Uint8Array([6, 49, 16, 129, 6, 18, 68, 49, 25, 129, 0, 18, 68, 49, 9, 50, 3, 18, 68, 49, 32, 50, 3, 18, 68, 129, 1, 67])); var TEXT_ENCODER = /*#__PURE__*/new TextEncoder(); var MAINNET_ANALYTICS_ENDPOINT = "https://api.algofi.org"; var TESTNET_ANALYTICS_ENDPOINT = "https://api-dev.algofi.org"; function getAnalyticsEndpoint(network) { if (network == exports.Network.MAINNET) { return MAINNET_ANALYTICS_ENDPOINT; } else { return TESTNET_ANALYTICS_ENDPOINT; } } // ENUMS (function (Network) { Network[Network["MAINNET"] = 0] = "MAINNET"; Network[Network["TESTNET"] = 1] = "TESTNET"; })(exports.Network || (exports.Network = {})); function getNetworkName(network) { if (network == exports.Network.MAINNET) { return "mainnet"; } else if (network == exports.Network.TESTNET) { return "testnet"; } else { throw "bad network"; } } function _regeneratorRuntime() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function () { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, $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 generator._invoke = function (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); } }; }(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; this._invoke = 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 maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (undefined === method) { if (context.delegate = null, "throw" === context.method) { if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel; context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return 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, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), 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 (object) { var 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 _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."); } function roundDown(amount, decimals) { return Math.floor(amount * Math.pow(10, decimals)) / Math.pow(10, decimals); } function roundUp(amount, decimals) { return Math.ceil(amount * Math.pow(10, decimals)) / Math.pow(10, decimals); } // FUNCTIONS function concatArrays(arrays) { // sum of individual array lengths var totalLength = arrays.reduce(function (acc, value) { return acc + value.length; }, 0); if (!arrays.length) return null; var result = new Uint8Array(totalLength); // for each array - copy it over result // next array is copied right after the previous one var length = 0; for (var _iterator = _createForOfIteratorHelperLoose(arrays), _step; !(_step = _iterator()).done;) { var array = _step.value; result.set(array, length); length += array.length; } return result; } function formatPrefixState(state) { var formattedState = {}; for (var _i = 0, _Object$entries = Object.entries(state); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _Object$entries[_i], key = _Object$entries$_i[0], value = _Object$entries$_i[1]; var indexUnderScore = key.indexOf("_"); // case when it is a prefix term if (indexUnderScore > 0) { var prefix = key.substring(0, indexUnderScore + 1); var hex = key.substring(indexUnderScore + 1); var formatted = Uint8Array.from(hex, function (e) { return e.charCodeAt(0); }); var number = formatted[7]; formattedState[prefix + number.toString()] = value; } else { formattedState[key] = value; } } return formattedState; } function parseAddressBytes(bytes) { return algosdk.encodeAddress(Buffer.from(bytes, "base64")); } function decodeBytes(bytes) { var result = new Uint8Array(bytes.length); for (var i = 0; i < bytes.length; ++i) { result[i] = bytes.charCodeAt(i); } return result; } function addressEquals(a, b) { return a.publicKey.length == b.publicKey.length && a.publicKey.every(function (val, index) { return val == b.publicKey[index]; }) && a.checksum.length == b.checksum.length && a.checksum.every(function (val, index) { return val == b.checksum[index]; }); } function composeTransactions(txnsToCompose) { var txns = []; for (var _iterator2 = _createForOfIteratorHelperLoose(txnsToCompose), _step2; !(_step2 = _iterator2()).done;) { var txnGroup = _step2.value; for (var _iterator3 = _createForOfIteratorHelperLoose(txnGroup), _step3; !(_step3 = _iterator3()).done;) { var _txn = _step3.value; txns.push(_txn); } } for (var _i2 = 0, _txns = txns; _i2 < _txns.length; _i2++) { var txn = _txns[_i2]; txn.group = undefined; } return algosdk.assignGroupID(txns); } // INTERFACE (function (TxnLoadMode) { TxnLoadMode[TxnLoadMode["REFRESH"] = 0] = "REFRESH"; TxnLoadMode[TxnLoadMode["REVERSE"] = 1] = "REVERSE"; })(exports.TxnLoadMode || (exports.TxnLoadMode = {})); var ParsedTransaction = function ParsedTransaction(transaction, protocol, app, action, params, assetsIn, assetsOut) { this.transactionId = transaction['id']; this.groupId = transaction['group']; this.block = transaction['confirmed-round']; this.time = transaction['round-time']; this.protocol = protocol; this.app = app; this.action = action; this.params = params; // flatten assets for (var _i = 0, _Object$entries = Object.entries(assetsIn); _i < _Object$entries.length; _i++) { var _Object$entries$_i = _Object$entries[_i], assetId = _Object$entries$_i[0], amount = _Object$entries$_i[1]; if (assetId in assetsOut && amount > assetsOut[assetId]) { assetsIn[assetId] -= assetsOut[assetId]; delete assetsOut[assetId]; } } this.assetsIn = assetsIn; this.assetsOut = assetsOut; }; /** * Function to get global state of an application * * @param {Algodv2} algodClient * * @return {dict<string,any>} dictionary of global state */ function getApplicationGlobalState(_x, _x2) { return _getApplicationGlobalState.apply(this, arguments); } /** * Function to get local state for an account info object * * @param {AccountInformation} accountInfo * * @return {dict<number,dict{string:any}>} dictionary of user local states */ function _getApplicationGlobalState() { _getApplicationGlobalState = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(algodClient, applicationId) { var response, results; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return algodClient.getApplicationByID(applicationId)["do"](); case 2: response = _context2.sent; results = {}; _context2.next = 6; return Promise.all(response.params["global-state"].map( /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(x) { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (x.value.type == 1) { results[Base64Encoder.decode(x.key)] = x.value.bytes; } else { results[Base64Encoder.decode(x.key)] = x.value.uint; } case 1: case "end": return _context.stop(); } } }, _callee); })); return function (_x12) { return _ref.apply(this, arguments); }; }())); case 6: return _context2.abrupt("return", results); case 7: case "end": return _context2.stop(); } } }, _callee2); })); return _getApplicationGlobalState.apply(this, arguments); } function getLocalStatesFromAccountInfo(_x3) { return _getLocalStatesFromAccountInfo.apply(this, arguments); } /** * Function to get local state for a given address and application * * @param {Algodv2} algodClient * @param {string} address * * @return {dict<number,dict{string:any}>} dictionary of user local states */ function _getLocalStatesFromAccountInfo() { _getLocalStatesFromAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(accountInfo) { var results; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: results = {}; _context5.next = 3; return Promise.all(accountInfo["apps-local-state"].map( /*#__PURE__*/function () { var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(appLocalState) { var localState; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: if (!appLocalState["key-value"]) { _context4.next = 7; break; } localState = {}; _context4.next = 4; return Promise.all(appLocalState["key-value"].map( /*#__PURE__*/function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(x) { var key; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: key = Base64Encoder.decode(x.key); if (x.value.type == 1) { localState[key] = x.value.bytes; } else { localState[key] = x.value.uint; } case 2: case "end": return _context3.stop(); } } }, _callee3); })); return function (_x14) { return _ref3.apply(this, arguments); }; }())); case 4: results[appLocalState.id] = localState; _context4.next = 8; break; case 7: results[appLocalState.id] = {}; case 8: case "end": return _context4.stop(); } } }, _callee4); })); return function (_x13) { return _ref2.apply(this, arguments); }; }())); case 3: return _context5.abrupt("return", results); case 4: case "end": return _context5.stop(); } } }, _callee5); })); return _getLocalStatesFromAccountInfo.apply(this, arguments); } function getLocalStates(_x4, _x5) { return _getLocalStates.apply(this, arguments); } /** * Function to get balances given an account info object * * @param {AccountInformation} accountInfo * * @return {dict<string,int>} dictionary of assets to amounts */ function _getLocalStates() { _getLocalStates = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(algodClient, address) { var results, accountInfo; return _regeneratorRuntime().wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: results = {}; _context8.next = 3; return algodClient.accountInformation(address)["do"](); case 3: accountInfo = _context8.sent; _context8.next = 6; return Promise.all(accountInfo["apps-local-state"].map( /*#__PURE__*/function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(appLocalState) { var localState; return _regeneratorRuntime().wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: if (!appLocalState["key-value"]) { _context7.next = 7; break; } localState = {}; _context7.next = 4; return Promise.all(appLocalState["key-value"].map( /*#__PURE__*/function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(x) { var key; return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: key = Base64Encoder.decode(x.key); if (x.value.type == 1) { localState[key] = x.value.bytes; } else { localState[key] = x.value.uint; } case 2: case "end": return _context6.stop(); } } }, _callee6); })); return function (_x16) { return _ref5.apply(this, arguments); }; }())); case 4: results[appLocalState.id] = localState; _context7.next = 8; break; case 7: results[appLocalState.id] = {}; case 8: case "end": return _context7.stop(); } } }, _callee7); })); return function (_x15) { return _ref4.apply(this, arguments); }; }())); case 6: return _context8.abrupt("return", results); case 7: case "end": return _context8.stop(); } } }, _callee8); })); return _getLocalStates.apply(this, arguments); } function getAccountBalancesFromAccountInfo(_x6) { return _getAccountBalancesFromAccountInfo.apply(this, arguments); } /** * Function to get balances for an account * * @param {Algodv2} algodClient * @param {string} address * * @return {dict<string,int>} dictionary of assets to amounts */ function _getAccountBalancesFromAccountInfo() { _getAccountBalancesFromAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(accountInfo) { var results; return _regeneratorRuntime().wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: results = {}; results[1] = accountInfo["amount"]; _context10.next = 4; return Promise.all(accountInfo["assets"].map( /*#__PURE__*/function () { var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(x) { return _regeneratorRuntime().wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: results[x["asset-id"]] = x["amount"]; case 1: case "end": return _context9.stop(); } } }, _callee9); })); return function (_x17) { return _ref6.apply(this, arguments); }; }())); case 4: return _context10.abrupt("return", results); case 5: case "end": return _context10.stop(); } } }, _callee10); })); return _getAccountBalancesFromAccountInfo.apply(this, arguments); } function getAccountBalances(_x7, _x8) { return _getAccountBalances.apply(this, arguments); } /** * Function to get min balance from an account info object * * @param {AccountInformation} accountInfo * * @return {number} min algo balance for an account */ function _getAccountBalances() { _getAccountBalances = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee12(algodClient, address) { var results, accountInfo; return _regeneratorRuntime().wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: results = {}; _context12.next = 3; return algodClient.accountInformation(address)["do"](); case 3: accountInfo = _context12.sent; results[1] = accountInfo["amount"]; _context12.next = 7; return Promise.all(accountInfo["assets"].map( /*#__PURE__*/function () { var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee11(x) { return _regeneratorRuntime().wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: results[x["asset-id"]] = x["amount"]; case 1: case "end": return _context11.stop(); } } }, _callee11); })); return function (_x18) { return _ref7.apply(this, arguments); }; }())); case 7: return _context12.abrupt("return", results); case 8: case "end": return _context12.stop(); } } }, _callee12); })); return _getAccountBalances.apply(this, arguments); } function getAccountMinBalanceFromAccountInfo(_x9) { return _getAccountMinBalanceFromAccountInfo.apply(this, arguments); } /** * Function to get min balance for an account * * @param {Algodv2} algodClient * @param {string} address * * @return {number} min algo balance for an account */ function _getAccountMinBalanceFromAccountInfo() { _getAccountMinBalanceFromAccountInfo = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee13(accountInfo) { return _regeneratorRuntime().wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: return _context13.abrupt("return", accountInfo["min-balance"]); case 1: case "end": return _context13.stop(); } } }, _callee13); })); return _getAccountMinBalanceFromAccountInfo.apply(this, arguments); } function getAccountMinBalance(_x10, _x11) { return _getAccountMinBalance.apply(this, arguments); } function _getAccountMinBalance() { _getAccountMinBalance = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee14(algodClient, address) { var accountInfo; return _regeneratorRuntime().wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return algodClient.accountInformation(address)["do"](); case 2: accountInfo = _context14.sent; return _context14.abrupt("return", accountInfo["min-balance"]); case 4: case "end": return _context14.stop(); } } }, _callee14); })); return _getAccountMinBalance.apply(this, arguments); } function storeTransferDetails(txn, store) { if (txn["tx-type"] == "pay") { store[ALGO_ASSET_ID] = txn['payment-transaction']['amount']; } else if (txn["tx-type"] == "axfer") { store[txn['asset-transfer-transaction']['asset-id']] = txn['asset-transfer-transaction']['amount']; } } // IMPORTS // INTERFACE var BaseLendingUser = /*#__PURE__*/function () { function BaseLendingUser(algofiClient, address) { this.v2 = algofiClient.lending.v2.getUser(address); } var _proto = BaseLendingUser.prototype; _proto.loadState = /*#__PURE__*/function () { var _loadState = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(userLocalStates) { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.v2.loadState(userLocalStates); case 2: case "end": return _context.stop(); } } }, _callee, this); })); function loadState(_x) { return _loadState.apply(this, arguments); } return loadState; }(); return BaseLendingUser; }(); // IMPORTS // INTERFACE var BaseStakingUser = /*#__PURE__*/function () { function BaseStakingUser(algofiClient, address) { this.v1 = algofiClient.staking.v1.getUser(address); this.v2 = algofiClient.staking.v2.getUser(address); } var _proto = BaseStakingUser.prototype; _proto.loadState = /*#__PURE__*/function () { var _loadState = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(userLocalStates) { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.v1.loadState(userLocalStates); case 2: _context.next = 4; return this.v2.loadState(userLocalStates); case 4: case "end": return _context.stop(); } } }, _callee, this); })); function loadState(_x) { return _loadState.apply(this, arguments); } return loadState; }(); return BaseStakingUser; }(); // IMPORTS // INTERFACE var BaseLendingUser$1 = /*#__PURE__*/function () { function BaseLendingUser(algofiClient, address) { this.v1 = algofiClient.governance.v1.getUser(address); this.network = algofiClient.network; } var _proto = BaseLendingUser.prototype; _proto.loadState = /*#__PURE__*/function () { var _loadState = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(userLocalStates) { return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.v1.loadState(userLocalStates); case 2: case "end": return _context.stop(); } } }, _callee, this); })); function loadState(_x) { return _loadState.apply(this, arguments); } return loadState; }(); return BaseLendingUser; }(); var AlgofiUser = /*#__PURE__*/function () { /** * Constructor for the algofi client class. * * @param algofiClient - algofi client * @param address - address for user */ function AlgofiUser(algofiClient, address) { // account state this.balances = {}; this.algofiClient = algofiClient; this.algod = this.algofiClient.algod; this.indexer = this.algofiClient.indexer; this.address = address; // lending this.lending = new BaseLendingUser(this.algofiClient, this.address); // staking this.staking = new BaseStakingUser(this.algofiClient, this.address); // governance this.governance = new BaseLendingUser$1(this.algofiClient, this.address); } /** * Function to load the states of all of the sub users on the algofi user * class. */ var _proto = AlgofiUser.prototype; _proto.loadState = /*#__PURE__*/ function () { var _loadState = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() { var accountInfo, localStates, loadLendingPromise, loadStakingPromise, loadGovernancePromise; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.algod.accountInformation(this.address)["do"](); case 2: accountInfo = _context.sent; _context.next = 5; return getLocalStatesFromAccountInfo(accountInfo); case 5: localStates = _context.sent; _context.next = 8; return getAccountBalancesFromAccountInfo(accountInfo); case 8: this.balances = _context.sent; _context.next = 11; return getAccountMinBalanceFromAccountInfo(accountInfo); case 11: this.minBalance = _context.sent; // update protocol user classes loadLendingPromise = this.lending.loadState(localStates); // update user staking state loadStakingPromise = this.staking.loadState(localStates); // update user governance state loadGovernancePromise = this.governance.loadState(localStates); // await completion _context.next = 17; return Promise.all([loadLendingPromise, loadStakingPromise, loadGovernancePromise]); case 17: case "end": return _context.stop(); } } }, _callee, this); })); function loadState() { return _loadState.apply(this, arguments); } return loadState; }() /** * Function to determine whether someone is opted into an asset or not. * * @param assetId - asset id * @returns whether or not the user is opted into the asset id. */ ; _proto.isOptedInToAsset = function isOptedInToAsset(assetId) { if (assetId in this.balances) { return true; } else { return false; } }; _proto.getTransactionHistory = /*#__PURE__*/function () { var _getTransactionHistory = /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(mode) { var accountTxns, txnIdx, txn; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: accountTxns = {}; if (mode == exports.TxnLoadMode.REFRESH) { // clear transactions this.transactions = []; } if (!(mode == exports.TxnLoadMode.REVERSE && this.transactions.length > 0)) { _context2.next = 9; break; } _context2.next = 6; return this.indexer.lookupAccountTransactions(this.address).maxRound(this.transactions.slice(-1)[0].block).limit(500)["do"](); case 6: accountTxns = _context2.sent; _context2.next = 12; break; case 9: _context2.next = 11; return this.indexer.lookupAccountTransactions(this.address).limit(500)["do"](); case 11: accountTxns = _context2.sent; case 12: for (txnIdx = 0; txnIdx < accountTxns["transactions"].length; txnIdx++) { txn = accountTxns["transactions"][txnIdx]; if (txn["tx-type"] == "appl") { if (this.algofiClient.lending.v2.isLendingTransaction(txn)) { this.lending.v2.parseTransaction(accountTxns["transactions"], txnIdx, this.transactions); } else if (this.algofiClient.amm.v1.isAMMTransaction(txn)) { this.algofiClient.amm.v1.parseTransaction(accountTxns["transactions"], txnIdx, this.transactions); } } } case 13: case "end": return _context2.stop(); } } }, _callee2, this); })); function getTransactionHistory(_x) { return _getTransactionHistory.apply(this, arguments); } return getTransactionHistory; }(); return AlgofiUser; }(); var _AssetConfigs; var BANK_ASSET_ID$1 = 900652777; // INTERFACE var AssetConfig = /** * Constructor for the asset config class. * * @param name - asset name * @param assetId - asset id * @param decimals - asset decimals */ function AssetConfig(name, unitName, assetId, decimals, defaultPrice) { this.name = name; this.unitName = unitName; this.assetId = assetId; this.decimals = decimals; this.defaultPrice = defaultPrice; }; var AssetConfigs = (_AssetConfigs = {}, _AssetConfigs[exports.Network.MAINNET] = { 1: /*#__PURE__*/new AssetConfig("ALGO", "ALGO", 1, 6, undefined), 818179690: /*#__PURE__*/new AssetConfig("AF-BANK-ALGO-STANDARD", "AF-BANK", 818179690, 6, undefined), 31566704: /*#__PURE__*/new AssetConfig("USDC", "USDC", 31566704, 6, 1.0), 818182311: /*#__PURE__*/new AssetConfig("AF-BANK-USDC-STANDARD", "AF-BANK", 818182311, 6, undefined), 386192725: /*#__PURE__*/new AssetConfig("goBTC", "goBTC", 386192725, 8, undefined), 818184214: /*#__PURE__*/new AssetConfig("AF-BANK-GOBTC-STANDARD", "AF-BANK", 818184214, 6, undefined), 386195940: /*#__PURE__*/new AssetConfig("goETH", "goETH", 386195940, 8, undefined), 818188553: /*#__PURE__*/new AssetConfig("AF-BANK-GOETH-STANDARD", "AF-BANK", 818188553, 6, undefined), 312769: /*#__PURE__*/new AssetConfig("USDT", "USDT", 312769, 6, 1.0), 818190568: /*#__PURE__*/new AssetConfig("AF-BANK-USDT-STANDARD", "AF-BANK", 818190568, 6, undefined), 841126810: /*#__PURE__*/new AssetConfig("STBL2", "STBL2", 841126810, 6, 1.0), 841157954: /*#__PURE__*/new AssetConfig("AF-BANK_STBL2-STABLE", "AF-BANK", 841157954, 6, undefined), // VAULT 879951266: /*#__PURE__*/new AssetConfig("AF-BANK-ALGO-VAULT", "AF-BANK", 87995126