hc-sdk
Version:
hc-sdk is a library for working with the HuaChain Horizon server.
248 lines (209 loc) • 11.8 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.FederationServer = exports.FEDERATION_RESPONSE_MAX_SIZE = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _axios = require('axios');
var _axios2 = _interopRequireDefault(_axios);
var _urijs = require('urijs');
var _urijs2 = _interopRequireDefault(_urijs);
var _hcBase = require('hc-base');
var _config = require('./config');
var _errors = require('./errors');
var _stellar_toml_resolver = require('./stellar_toml_resolver');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// FEDERATION_RESPONSE_MAX_SIZE is the maximum size of response from a federation server
var FEDERATION_RESPONSE_MAX_SIZE = exports.FEDERATION_RESPONSE_MAX_SIZE = 100 * 1024;
/**
* FederationServer handles a network connection to a
* [federation server](https://www.stellar.org/developers/guides/concepts/federation.html)
* instance and exposes an interface for requests to that instance.
* @constructor
* @param {string} serverURL The federation server URL (ex. `https://acme.com/federation`).
* @param {string} domain Domain this server represents
* @param {object} [opts] options object
* @param {boolean} [opts.allowHttp] - Allow connecting to http servers, default: `false`. This must be set to false in production deployments! You can also use {@link Config} class to set this globally.
* @param {number} [opts.timeout] - Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue. You can also use {@link Config} class to set this globally.
* @returns {void}
*/
var FederationServer = exports.FederationServer = function () {
function FederationServer(serverURL, domain) {
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
_classCallCheck(this, FederationServer);
// TODO `domain` regexp
this.serverURL = (0, _urijs2.default)(serverURL);
this.domain = domain;
var allowHttp = _config.Config.isAllowHttp();
if (typeof opts.allowHttp !== 'undefined') {
allowHttp = opts.allowHttp;
}
this.timeout = _config.Config.getTimeout();
if (typeof opts.timeout === 'number') {
this.timeout = opts.timeout;
}
if (this.serverURL.protocol() !== 'https' && !allowHttp) {
throw new Error('Cannot connect to insecure federation server');
}
}
/**
* A helper method for handling user inputs that contain `destination` value.
* It accepts two types of values:
*
* * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about
* federation server in `stellar.toml` file for a given domain. It returns a `Promise` which resolves if federation
* server exists and user has been found and rejects in all other cases.
* * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which
* resolves if Account ID is valid and rejects in all other cases. Please note that this method does not check
* if the account actually exists in a ledger.
*
* Example:
* ```js
* StellarSdk.FederationServer.resolve('bob*stellar.org')
* .then(federationRecord => {
* // {
* // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS',
* // memo_type: 'id',
* // memo: 100
* // }
* });
* ```
*
* @see <a href="https://www.stellar.org/developers/guides/concepts/federation.html" target="_blank">Federation doc</a>
* @see <a href="https://www.stellar.org/developers/guides/concepts/stellar-toml.html" target="_blank">Stellar.toml doc</a>
* @param {string} value Stellar Address (ex. `bob*stellar.org`)
* @param {object} [opts] Options object
* @param {boolean} [opts.allowHttp] - Allow connecting to http servers, default: `false`. This must be set to false in production deployments!
* @param {number} [opts.timeout] - Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue.
* @returns {Promise} `Promise` that resolves to a JSON object with this shape:
* * `account_id` - Account ID of the destination,
* * `memo_type` (optional) - Memo type that needs to be attached to a transaction,
* * `memo` (optional) - Memo value that needs to be attached to a transaction.
*/
_createClass(FederationServer, [{
key: 'resolveAddress',
/**
* Get the federation record if the user was found for a given Stellar address
* @see <a href="https://www.stellar.org/developers/guides/concepts/federation.html" target="_blank">Federation doc</a>
* @param {string} address Stellar address (ex. `bob*stellar.org`). If `FederationServer` was instantiated with `domain` param only username (ex. `bob`) can be passed.
* @returns {Promise} Promise that resolves to the federation record
*/
value: function resolveAddress(address) {
var stellarAddress = address;
if (address.indexOf('*') < 0) {
if (!this.domain) {
return Promise.reject(new Error('Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object.'));
}
stellarAddress = address + '*' + this.domain;
}
var url = this.serverURL.query({ type: 'name', q: stellarAddress });
return this._sendRequest(url);
}
/**
* Given an account ID, get their federation record if the user was found
* @see <a href="https://www.stellar.org/developers/guides/concepts/federation.html" target="_blank">Federation doc</a>
* @param {string} accountId Account ID (ex. `GBYNR2QJXLBCBTRN44MRORCMI4YO7FZPFBCNOKTOBCAAFC7KC3LNPRYS`)
* @returns {Promise} A promise that resolves to the federation record
*/
}, {
key: 'resolveAccountId',
value: function resolveAccountId(accountId) {
var url = this.serverURL.query({ type: 'id', q: accountId });
return this._sendRequest(url);
}
/**
* Given a transactionId, get the federation record if the sender of the transaction was found
* @see <a href="https://www.stellar.org/developers/guides/concepts/federation.html" target="_blank">Federation doc</a>
* @param {string} transactionId Transaction ID (ex. `3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889`)
* @returns {Promise} A promise that resolves to the federation record
*/
}, {
key: 'resolveTransactionId',
value: function resolveTransactionId(transactionId) {
var url = this.serverURL.query({ type: 'txid', q: transactionId });
return this._sendRequest(url);
}
}, {
key: '_sendRequest',
value: function _sendRequest(url) {
var timeout = this.timeout;
return _axios2.default.get(url.toString(), {
maxContentLength: FEDERATION_RESPONSE_MAX_SIZE,
timeout: timeout
}).then(function (response) {
if (typeof response.data.memo !== 'undefined' && typeof response.data.memo !== 'string') {
throw new Error('memo value should be of type string');
}
return response.data;
}).catch(function (response) {
if (response instanceof Error) {
if (response.message.match(/^maxContentLength size/)) {
throw new Error('federation response exceeds allowed size of ' + FEDERATION_RESPONSE_MAX_SIZE);
} else {
return Promise.reject(response);
}
} else {
return Promise.reject(new _errors.BadResponseError('Server query failed. Server responded: ' + response.status + ' ' + response.statusText, response.data));
}
});
}
}], [{
key: 'resolve',
value: function resolve(value) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// Check if `value` is in account ID format
if (value.indexOf('*') < 0) {
if (!_hcBase.StrKey.isValidEd25519PublicKey(value)) {
return Promise.reject(new Error('Invalid Account ID'));
}
return Promise.resolve({ account_id: value });
}
var addressParts = value.split('*');
var _addressParts = _slicedToArray(addressParts, 2),
domain = _addressParts[1];
if (addressParts.length !== 2 || !domain) {
return Promise.reject(new Error('Invalid Stellar address'));
}
return FederationServer.createForDomain(domain, opts).then(function (federationServer) {
return federationServer.resolveAddress(value);
});
}
/**
* Creates a `FederationServer` instance based on information from
* [stellar.toml](https://www.stellar.org/developers/guides/concepts/stellar-toml.html)
* file for a given domain.
*
* If `stellar.toml` file does not exist for a given domain or it does not
* contain information about a federation server Promise will reject.
* ```js
* StellarSdk.FederationServer.createForDomain('acme.com')
* .then(federationServer => {
* // federationServer.resolveAddress('bob').then(...)
* })
* .catch(error => {
* // stellar.toml does not exist or it does not contain information about federation server.
* });
* ```
* @see <a href="https://www.stellar.org/developers/guides/concepts/stellar-toml.html" target="_blank">Stellar.toml doc</a>
* @param {string} domain Domain to get federation server for
* @param {object} [opts] Options object
* @param {boolean} [opts.allowHttp] - Allow connecting to http servers, default: `false`. This must be set to false in production deployments!
* @param {number} [opts.timeout] - Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue.
* @returns {Promise} `Promise` that resolves to a FederationServer object
*/
}, {
key: 'createForDomain',
value: function createForDomain(domain) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return _stellar_toml_resolver.StellarTomlResolver.resolve(domain, opts).then(function (tomlObject) {
if (!tomlObject.FEDERATION_SERVER) {
return Promise.reject(new Error('stellar.toml does not contain FEDERATION_SERVER field'));
}
return new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts);
});
}
}]);
return FederationServer;
}();
;