UNPKG

sila-sdk

Version:
948 lines (911 loc) 83.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _randombytes = _interopRequireDefault(require("randombytes")); var _ethers = require("ethers"); var _uuid = _interopRequireDefault(require("uuid4")); var _fs = _interopRequireDefault(require("fs")); var _crypto = _interopRequireDefault(require("crypto")); var _lodash = _interopRequireWildcard(require("lodash")); var _regeneratorRuntime2 = _interopRequireDefault(require("regenerator-runtime")); var _axios = _interopRequireDefault(require("axios")); var _formData = _interopRequireDefault(require("form-data")); var _transactionFilters = _interopRequireDefault(require("./models/transactionFilters")); var _user = _interopRequireDefault(require("./models/user")); var _wallet = _interopRequireDefault(require("./models/wallet")); var _walletFilters = _interopRequireDefault(require("./models/walletFilters")); var _post = require("./utils/post"); var _package = _interopRequireDefault(require("../package.json")); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } // eslint-disable-line no-unused-vars var appKey = null; var appHandle = null; var sandbox = true; var env = 'SANDBOX'; var baseUrl = 'https://sandbox.silamoney.com/0.2/'; var logging = false; var url = function url(path) { return baseUrl + path; }; var getBalanceURL = function getBalanceURL() { var balanceURL = ''; switch (env) { case 'PROD': balanceURL = sandbox ? 'https://sandbox.silatokenapi.silamoney.com/silaBalance' : 'https://silatokenapi.silamoney.com/silaBalance'; break; default: balanceURL = 'https://test.silatokenapi.silamoney.com/silaBalance'; } return balanceURL; }; /** * * @param {String} message The message to sign * @param {*} key The key to sign the message with */ var sign = function sign(message, key) { if (!appKey || !key) { throw new Error('Unable to sign request: keys not set'); } var hash = _ethers.ethers.solidityPackedKeccak256(['string'], [message]); var normalizeKey = key.startsWith('0x') ? key : '0x' + key; var signingKey = new _ethers.ethers.SigningKey(normalizeKey); var signatureObject = signingKey.sign(hash); var r = signatureObject.r.slice(2); var s = signatureObject.s.slice(2); var yParity = signatureObject.yParity === 1 ? '1c' : '1b'; var signature = "".concat(r).concat(s).concat(yParity); if (logging && env !== 'PROD') { console.log('*** MESSAGE STRING ***'); console.log(message); console.log('*** HASH ***'); console.log(hash); console.log('*** SIGNING WITH KEY ***'); console.log(key); console.log('*** SIGNATURE ***'); console.log(signature); } return signature; }; var configureUrl = function configureUrl() { switch (env) { case 'TEST': baseUrl = 'https://test4api.silamoney.com/0.2/'; break; case 'PROD': baseUrl = 'https://api.silamoney.com/0.2/'; break; case 'STAGE': baseUrl = 'https://stageapi.silamoney.com/0.2/'; break; default: baseUrl = 'https://sandbox.silamoney.com/0.2/'; break; } }; /** * * @param {*} opts * @param {String} key * @param {String} businessPrivateKey */ var signOpts = function signOpts(opts, key, businessPrivateKey) { var options = _lodash["default"].cloneDeep(opts); if (opts.body.header) { options.headers = {}; options.headers['User-Agent'] = "SilaSDK-node/".concat(_package["default"].version); var bodyString = JSON.stringify(options.body); options.headers.authsignature = sign(bodyString, appKey); if (key) options.headers.usersignature = sign(bodyString, key); if (businessPrivateKey) options.headers.businesssignature = sign(bodyString, businessPrivateKey); } return options; }; /** * Hashes a file * @param {String} filePath The full path to the file * @param {String} algorithm The algorithm of the hash */ var hashFile = function hashFile(filePath, algorithm) { var promise = new Promise(function (res, rej) { var hash = _crypto["default"].createHash(algorithm); var file = _fs["default"].createReadStream(filePath, { autoClose: true }); file.on('data', function (data) { hash.update(data); }).on('end', function () { var digest = hash.digest('hex'); return res(digest); }).on('error', function (error) { rej(error); }); }); return promise; }; /** * Hashes a fileBuffer * @param {Unit-8 Array} fileBuffer of the file * @param {String} algorithm The algorithm of the hash */ var hashFileObject = function hashFileObject(fileBuffer, algorithm) { var promise = new Promise(function (res, rej) { var digest = _crypto["default"].createHash(algorithm).update(fileBuffer).digest('hex'); return res(digest); }); return promise; }; /** * * @param {Object} msg The header message * @param {String} handle The user handle * @param {String} businessHandle */ var setHeaders = function setHeaders(msg, handle, businessHandle) { var message = msg; message.header.user_handle = handle; message.header.business_handle = businessHandle; message.header.app_handle = appHandle; message.header.reference = (0, _uuid["default"])(); message.header.created = Math.floor(Date.now() / 1000); message.header.crypto = 'ETH'; message.header.version = '0.2'; return message; }; var postFile = function postFile(options, filePath, fileObject) { var promise = new Promise(function (res, rej) { if (logging && env !== 'PROD') { console.log('*** REQUEST ***'); console.log(options.body); } if (fileObject && Object.keys(fileObject).length !== 0) { var data = new _formData["default"](); data.append('data', JSON.stringify(options.body)); for (var key in fileObject) { data.append(key, fileObject[key]); } var config = { method: 'post', url: options.uri, headers: _objectSpread(_objectSpread({}, options.headers), data.getHeaders()), data: data }; (0, _axios["default"])(config).then(function (response) { res({ statusCode: response.status || response.statusCode, headers: response.headers, data: response.data }); })["catch"](function (error) { var _error$response, _error$response2, _error$response3, _error$response4; res({ statusCode: ((_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.status) || ((_error$response2 = error.response) === null || _error$response2 === void 0 ? void 0 : _error$response2.statusCode), headers: (_error$response3 = error.response) === null || _error$response3 === void 0 ? void 0 : _error$response3.headers, data: (_error$response4 = error.response) === null || _error$response4 === void 0 ? void 0 : _error$response4.data }); }); } else { var formData = new _formData["default"](); formData.append('data', JSON.stringify(options.body)); for (var _key in filePath) { formData.append(_key, filePath[_key]); } var _config = { method: 'post', url: options.uri, headers: _objectSpread(_objectSpread({}, options.headers), formData.getHeaders()), data: formData }; (0, _axios["default"])(_config).then(function (response) { res({ statusCode: response.status || response.statusCode, headers: response.headers, data: response.data }); })["catch"](function (error) { var _error$response5, _error$response6, _error$response7, _error$response8; res({ statusCode: ((_error$response5 = error.response) === null || _error$response5 === void 0 ? void 0 : _error$response5.status) || ((_error$response6 = error.response) === null || _error$response6 === void 0 ? void 0 : _error$response6.statusCode), headers: (_error$response7 = error.response) === null || _error$response7 === void 0 ? void 0 : _error$response7.headers, data: (_error$response8 = error.response) === null || _error$response8 === void 0 ? void 0 : _error$response8.data }); }); } }); return promise; }; /** * * @param {String} path The path of the request * @param {Object} body The body of the request * @param {String} privateKey The user's private key */ var makeRequest = function makeRequest(path, body) { var privateKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var business_private_key = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : undefined; var requestMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'post'; var opts = { method: requestMethod, uri: url(path), json: true, body: body }; if (path == 'get_document') { opts['encoding'] = 'binary'; } opts = signOpts(opts, privateKey, business_private_key); return (0, _post.post)(opts, env, logging); }; var makeFileRequest = function makeFileRequest(path, body, filePath, fileObject, privateKey) { var opts = { uri: url(path), body: body }; opts = signOpts(opts, privateKey); return postFile(opts, filePath, fileObject); }; /** * Returns the handle with the .silamoney.eth suffix if not present * @param {String} handle The handle */ var getFullHandle = function getFullHandle(handle) { var fullHandle = String(handle); if (fullHandle && !fullHandle.endsWith('.silamoney.eth')) { fullHandle += '.silamoney.eth'; } return fullHandle; }; /** * * @param {String} queryParameters The current query parameters * @param {String} name The name of the query parameter * @param {String} value The value of the query parameter */ var getQueryParameter = function getQueryParameter(queryParameters, name, value) { var newQueryParameters = queryParameters; if (value !== undefined && value !== null) { newQueryParameters += newQueryParameters.length > 0 ? '&' : '?'; newQueryParameters += "".concat(name, "=").concat(value); } return newQueryParameters; }; var getQueryParameters = function getQueryParameters(parameters) { var queryParameters = ''; if (parameters) { queryParameters = getQueryParameter(queryParameters, 'page', parameters.page); queryParameters = getQueryParameter(queryParameters, 'per_page', parameters.perPage); queryParameters = getQueryParameter(queryParameters, 'order', parameters.order); queryParameters = getQueryParameter(queryParameters, 'sort_ascending', parameters.sortAscending); } return queryParameters; }; /** * Makes a call to /check_handle endpoint. * @param {String} handle The user handle to check if it's available */ var checkHandle = function checkHandle(handle) { var fullHandle = getFullHandle(handle); var message = setHeaders({ header: {} }, fullHandle); message.message = 'header_msg'; return makeRequest('check_handle', message); }; /** * Makes a call to /register endpoint. * @param {User} user */ var register = function register(user) { var handle = getFullHandle(user.handle); var message = setHeaders({ header: {} }, handle); message.message = 'entity_msg'; if (user.city || user.zip || user.state || user.address || user.addressAlias || user.addresAlias || user.address2 || user.country) { message.address = {}; message.address.city = user.city; message.address.postal_code = user.zip; message.address.state = user.state; message.address.street_address_1 = user.address; message.address.street_address_2 = user.address2; message.address.address_alias = user.addressAlias ? user.addressAlias : user.addresAlias; message.address.country = user.country ? user.country : 'US'; } if (user.contactAlias || user.phone || user.email) { message.contact = {}; message.contact.contact_alias = user.contactAlias; message.contact.phone = user.phone; message.contact.email = user.email; } if (user.cryptoAddress || user.cryptoAlias) { message.crypto_entry = {}; message.crypto_entry.crypto_address = user.cryptoAddress; message.crypto_entry.crypto_code = 'ETH'; message.crypto_entry.crypto_alias = user.cryptoAlias; } if (user.firstName || user.lastName || user.entity_name || user.business_type || user.businessTypeUuid || user.business_website || user.doing_business_as || user.naics_code) { message.entity = {}; message.entity.birthdate = user.dateOfBirth; message.entity.first_name = user.firstName; message.entity.last_name = user.lastName; message.entity.entity_name = user.entity_name ? user.entity_name : ''; message.entity.relationship = 'user'; if (user.type) message.entity.type = user.type;else message.entity.type = user.business_type || user.businessTypeUuid ? 'business' : 'individual'; message.entity.business_type = user.business_type; message.entity.business_website = user.business_website; message.entity.doing_business_as = user.doing_business_as; message.entity.naics_code = user.naics_code; message.entity.business_type_uuid = user.businessTypeUuid; message.entity.registration_state = user.registration_state; } if (user.id_document) { message.id_document = {}; message.id_document.doc_type = user.doc_type; message.id_document.doc_id = user.doc_id; if (user.doc_state) message.id_document.doc_state = user.doc_state; if (user.doc_country) message.id_document.doc_country = user.doc_country; } if (user.ssn || user.ein) { message.identity = {}; message.identity.identity_value = user.ssn ? user.ssn : user.ein; message.identity.identity_alias = user.ssn ? 'SSN' : 'EIN'; } return makeRequest('register', message); }; /** * Makes a call to /request_kyc endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} kycLevel The custom kyc level */ var requestKYC = function requestKYC(handle, privateKey) { var kycLevel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var fullHandle = getFullHandle(handle); var message = setHeaders({ header: {} }, fullHandle); message.message = 'header_msg'; if (kycLevel) message.kyc_level = kycLevel; return makeRequest('request_kyc', message, privateKey); }; /** * Makes a call to /check_kyc endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} kycLevel The custom kyc level */ var checkKYC = function checkKYC(handle, privateKey) { var kycLevel = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var fullHandle = getFullHandle(handle); var message = setHeaders({ header: {} }, fullHandle); message.message = 'header_msg'; if (kycLevel) message.kyc_level = kycLevel; return makeRequest('check_kyc', message, privateKey); }; /** * Makes a call to /link_account endpoint. * This method handles the direct account link flow * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} accountNumber The account number * @param {String} routingNumber The routing number * @param {String} accountName The account nickname * @param {String} accountType The account type */ var linkAccountDirect = function linkAccountDirect(handle, privateKey, accountNumber, routingNumber) { var accountName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; var accountType = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : undefined; var fullHandle = getFullHandle(handle); var message = setHeaders({ header: {} }, fullHandle); message.message = 'link_account_msg'; message.account_number = accountNumber; message.routing_number = routingNumber; if (accountType) message.account_type = accountType; if (accountName) message.account_name = accountName; return makeRequest('link_account', message, privateKey); }; /** * Makes a call to /link_account endpoint. * This method handles the MX account link flow * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} providerTokenType The token type * @param {String} providerToken The token itself * @param {String} accountName The account nickname * @param {String} accountId The account id */ var linkAccountMX = function linkAccountMX(handle, privateKey, providerTokenType, providerToken) { var accountName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; var accountId = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : undefined; var fullHandle = getFullHandle(handle); var message = setHeaders({ header: {} }, fullHandle); message.message = 'link_account_msg'; message.provider = 'mx'; message.provider_token_type = providerTokenType; message.provider_token = providerToken; if (accountName) message.account_name = accountName; if (accountId) message.selected_account_id = accountId; return makeRequest('link_account', message, privateKey); }; /** * Makes a call to /link_account endpoint. * This method handles the plaid's token flow. * @param {String} handle The user hanlde * @param {String} privateKey The user's wallet private key * @param {String} publicToken Plaid's public token * @param {String} accountName The account nickname * @param {String} accountId The account id * */ var linkAccount = function linkAccount(handle, privateKey, plaidToken) { var accountName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : undefined; var accountId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; var plaidTokenType = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : undefined; var fullHandle = getFullHandle(handle); var message = setHeaders({ header: {} }, fullHandle); message.message = 'link_account_msg'; message.plaid_token = plaidToken; message.plaid_token_type = plaidTokenType; if (accountId) message.selected_account_id = accountId; if (accountName) message.account_name = accountName; return makeRequest('link_account', message, privateKey); }; /** * Makes a call to /issue_sila endpoint. * @param {Number} amount The amount of sila tokens to issue * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} accountName The nickname of the account to debit from. It defaults to 'default' // Optional, OR "card_name": "default", never both. * @param {String} descriptor Optional. Max Length 100. Note that only the first 10 characters show on the resulting bank statement. * @param {String} businessUuid Optional. UUID of a business with an approved ACH name. The format should be a UUID string. * @param {String} processingType Optional. Choice field. Examples: STANDARD_ACH or SAME_DAY_ACH * @param {String} cardName The nickname of the card to debit from. It defaults to 'default' // Optional, OR "account_name": "default", never both. * @param {String} sourceId source account id to debit from (optional) * @param {String} destinationId destination account id for credit (optional) * @param {String} transactionIdempotencyId Optional. UUID to uniquely identify the transaction to make it idempotent. * @param {String} transactionIdempotencyIdentifier Optional. String to uniquely identify the transaction to make it idempotent. */ var issueSila = function issueSila(amount, handle, privateKey) { var accountName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : undefined; var descriptor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; var businessUuid = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : undefined; var processingType = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : undefined; var cardName = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : undefined; var sourceId = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : undefined; var destinationId = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : undefined; var transactionIdempotencyId = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : undefined; var transactionIdempotencyIdentifier = arguments.length > 11 && arguments[11] !== undefined ? arguments[11] : undefined; var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.amount = amount; body.message = 'issue_msg'; if (cardName == undefined && accountName == undefined && sourceId == undefined) { accountName = 'default'; } body.account_name = accountName; if (cardName !== undefined) { body.card_name = cardName; } if (sourceId !== undefined) { body.source_id = sourceId; } if (destinationId !== undefined) { body.destination_id = destinationId; } if (descriptor) body.descriptor = descriptor; if (businessUuid) body.business_uuid = businessUuid; if (processingType) body.processing_type = processingType; if (transactionIdempotencyId) body.transaction_idempotency_id = transactionIdempotencyId; if (transactionIdempotencyIdentifier) { body.transaction_idempotency_identifier = transactionIdempotencyIdentifier; } return makeRequest('issue_sila', body, privateKey); }; /** * Makes a call to /redeem_sila endpoint. * @param {Number} amount The amount of sila tokens to reedem * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} accountName The account nickname to credit with the tokens' value. * @param {String} descriptor Optional. Max Length 100 * @param {String} businessUuid Optional. UUID of a business with an approved ACH name. The format should be a UUID string. * @param {String} processingType Optional. Choice field. Examples: STANDARD_ACH or SAME_DAY_ACH or CARD * @param {String} cardName The nickname of the card to debit from. Optional, OR "account_name": "default", never both. * @param {String} sourceId source account id to debit from (optional) * @param {String} destinationId destination account id for credit (optional) * @param {String} transactionIdempotencyId Optional. UUID to uniquely identify the transaction to make it idempotent. * @param {String} transactionIdempotencyIdentifier Optional. String to uniquely identify the transaction to make it idempotent. */ var redeemSila = function redeemSila(amount, handle, privateKey) { var accountName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : undefined; var descriptor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; var businessUuid = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : undefined; var processingType = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : undefined; var cardName = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : undefined; var sourceId = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : undefined; var destinationId = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : undefined; var transactionIdempotencyId = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : undefined; var transactionIdempotencyIdentifier = arguments.length > 11 && arguments[11] !== undefined ? arguments[11] : undefined; var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.amount = amount; body.message = 'redeem_msg'; if (cardName == undefined && accountName == undefined && sourceId == undefined) { accountName = 'default'; } body.account_name = accountName; if (cardName !== undefined) { body.card_name = cardName; } if (sourceId !== undefined) { body.source_id = sourceId; } if (destinationId !== undefined) { body.destination_id = destinationId; } if (descriptor) body.descriptor = descriptor; if (businessUuid) body.business_uuid = businessUuid; body.processing_type = processingType; if (transactionIdempotencyId) body.transaction_idempotency_id = transactionIdempotencyId; if (transactionIdempotencyIdentifier) { body.transaction_idempotency_identifier = transactionIdempotencyIdentifier; } return makeRequest('redeem_sila', body, privateKey); }; /** * Makes a call to /transfer_sila endpoint. * @param {String} amount The amount of sila tokens to transfer * @param {String} handle The origin user handle * @param {String} privateKey The origin user's wallet private key * @param {String} destinationHandle The destination user handle * @param {String} walletNickname The destination user's wallet nickname (optional) * @param {String} walletAddress The destination user's wallet address (optional) * @param {String} descriptor The transaction descriptor (optional) * @param {String} businessUuid The UUID of the business for the ACH name (optional) * @param {String} sourceId source account id to debit from (optional) * @param {String} destinationId destination account id for credit (optional) * @param {String} transactionIdempotencyId Optional. UUID to uniquely identify the transaction to make it idempotent. * @param {String} transactionIdempotencyIdentifier Optional. String to uniquely identify the transaction to make it idempotent. */ var transferSila = function transferSila(amount, handle, privateKey, destinationHandle) { var walletNickname = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; var walletAddress = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : undefined; var descriptor = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : undefined; var businessUuid = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : undefined; var sourceId = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : undefined; var destinationId = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : undefined; var transactionIdempotencyId = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : undefined; var transactionIdempotencyIdentifier = arguments.length > 11 && arguments[11] !== undefined ? arguments[11] : undefined; var fullHandle = getFullHandle(handle); var fullDestination = getFullHandle(destinationHandle); var body = setHeaders({ header: {} }, fullHandle); body.amount = amount; body.destination_handle = fullDestination; if (walletNickname) body.destination_wallet = walletNickname; if (walletAddress) body.destination_address = walletAddress; if (descriptor) body.descriptor = descriptor; if (businessUuid) body.business_uuid = businessUuid; if (sourceId) body.source_id = sourceId; if (destinationId) body.destination_id = destinationId; if (transactionIdempotencyId) body.transaction_idempotency_id = transactionIdempotencyId; if (transactionIdempotencyIdentifier) { body.transaction_idempotency_identifier = transactionIdempotencyIdentifier; } return makeRequest('transfer_sila', body, privateKey); }; /** * Cancel a pending transaction under certain circumstances * @param {String} userHandle The user handle * @param {String} userPrivateKey The user's private key * @param {String} transactionId The transaction id to cancel */ var cancelTransaction = function cancelTransaction(userHandle, userPrivateKey, transactionId) { var fullHandle = getFullHandle(userHandle); var body = setHeaders({ header: {} }, fullHandle); body.transaction_id = transactionId; return makeRequest('cancel_transaction', body, userPrivateKey); }; var deleteRegistrationData = function deleteRegistrationData(path, handle, privateKey, uuid) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.uuid = uuid; return makeRequest("delete/".concat(path), body, privateKey); }; /** * Makes a call to /delete/email endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} email The user's new email */ var deleteEmail = function deleteEmail(handle, privateKey, uuid) { return deleteRegistrationData('email', handle, privateKey, uuid); }; /** * Makes a call to /delete/phone endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} uuid The user's new phone */ var deletePhone = function deletePhone(handle, privateKey, uuid) { return deleteRegistrationData('phone', handle, privateKey, uuid); }; /** * Makes a call to /delete/address endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} uuid The user's new address */ var deleteAddress = function deleteAddress(handle, privateKey, uuid) { return deleteRegistrationData('address', handle, privateKey, uuid); }; /** * Makes a call to /delete/identity endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} uuid The user's new identity */ var deleteIdentity = function deleteIdentity(handle, privateKey, uuid) { return deleteRegistrationData('identity', handle, privateKey, uuid); }; /** * Makes a call to /update/email endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {Object} email The updated email */ var updateEmail = function updateEmail(handle, privateKey, email) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.email = email.email; body.uuid = email.uuid; return makeRequest('update/email', body, privateKey); }; /** * Makes a call to /update/phone endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {Object} optional The updated phone * @param {String} optional.phone * @param {String} optional.uuid */ var updatePhone = function updatePhone(handle, privateKey) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$phone = _ref.phone, phone = _ref$phone === void 0 ? undefined : _ref$phone, _ref$uuid = _ref.uuid, uuid = _ref$uuid === void 0 ? undefined : _ref$uuid; var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.phone = phone; body.uuid = uuid; return makeRequest('update/phone', body, privateKey); }; /** * Makes a call to /update/address endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {Object} address The updated address */ var updateAddress = function updateAddress(handle, privateKey, address) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.address_alias = address.alias; body.street_address_2 = address.street_address_2; body.street_address_1 = address.street_address_1; body.city = address.city; body.state = address.state; body.postal_code = address.postal_code; body.country = address.country; body.uuid = address.uuid; return makeRequest('update/address', body, privateKey); }; /** * Makes a call to /update/identity endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {Object} identity The updated identity */ var updateIdentity = function updateIdentity(handle, privateKey, identity) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.identity_alias = identity.alias; body.identity_value = identity.value; body.uuid = identity.uuid; return makeRequest('update/identity', body, privateKey); }; /** * Update an existing entity (name, birthdate, or business data). * @param {String} handle The user handle * @param {String} privateKey The user's private key * @param {Object} entity The updated entity */ var updateEntity = function updateEntity(handle, privateKey, entity) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.first_name = entity.first_name; body.last_name = entity.last_name; body.entity_name = entity.entity_name; body.birthdate = entity.birthdate; body.business_type = entity.business_type; body.naics_code = entity.naics_code; body.doing_business_as = entity.doing_business_as; body.business_website = entity.business_website; body.registration_state = entity.registration_state; return makeRequest('update/entity', body, privateKey); }; /** * Makes a call to /add/email endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} email The user's new email */ var addEmail = function addEmail(handle, privateKey, email) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.email = email; return makeRequest('add/email', body, privateKey); }; /** * Makes a call to /add/phone endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} phone The user's new phone * @param {Object} optional */ var addPhone = function addPhone(handle, privateKey, phone) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.phone = phone; return makeRequest('add/phone', body, privateKey); }; /** * Makes a call to /add/identity endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {Object} identity The user's new identity alias * */ var addIdentity = function addIdentity(handle, privateKey, identity) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.identity_alias = identity.alias; body.identity_value = identity.value; return makeRequest('add/identity', body, privateKey); }; /** * Makes a call to /add/address endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {Object} address The user's new address */ var addAddress = function addAddress(handle, privateKey, address) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.address_alias = address.alias; body.street_address_2 = address.street_address_2; body.street_address_1 = address.street_address_1; body.city = address.city; body.state = address.state; body.postal_code = address.postal_code; body.country = address.country; return makeRequest('add/address', body, privateKey); }; /** * Makes a call to /get_accounts endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key */ var getAccounts = function getAccounts(handle, privateKey) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.message = 'get_accounts_msg'; return makeRequest('get_accounts', body, privateKey); }; /** * Makes a call to /get_account_balance endpoint. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} accountName The account name to retrieve the balance */ var getAccountBalance = function getAccountBalance(handle, privateKey, accountName) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.account_name = accountName; return makeRequest('get_account_balance', body, privateKey); }; /** * Makes a call to /plaid_sameday_auth endpoint. * The account used in this endpoint must be in the microdeposit_pending_manual_verification status. * @param {String} handle The user handle * @param {String} privateKey The user's wallet private key * @param {String} accountName The account nickname */ var plaidSamedayAuth = function plaidSamedayAuth(handle, privateKey, accountName) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.account_name = accountName; return makeRequest('plaid_sameday_auth', body, privateKey); }; /** * Makes a call to /register_wallet endpoint. * If you need a new wallet you can use the generateWallet method. * @param {String} handle The user handle * @param {String} privateKey An already registered user's wallet private key * @param {Wallet} wallet The new wallet */ var registerWallet = function registerWallet(handle, privateKey, wallet, nickname, defaultVal, statementsEnabled) { var fullHandle = getFullHandle(handle); var body = setHeaders({ header: {} }, fullHandle); body.wallet_verification_signature = sign(wallet.address, wallet.privateKey); body.wallet = {}; body.wallet.blockchain_address = wallet.address; body.wallet.blockchain_network = 'ETH'; if (statementsEnabled) body.wallet.statements_enabled = statementsEnabled; if (nickname) body.wallet.nickname = nickname; if (defaultVal) body.wallet["default"] = defaultVal; return makeRequest('register_wallet', body, privateKey); }; /** * Makes a call to /get_wallets endpoint and returns the list of wallets that match the filters * @param {String} handle The user handle * @param {String} privateKey Any of the user's registered wallet's private key * @param {WalletFilters} filters The filters used to narrow the search results */ var getWallets = function getWallets(handle, privateKey) { var filters = argu