MoralisSolanaApi.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. function ownKeys(object, enumerableOnly) {
  7. var keys = Object.keys(object);
  8. if (Object.getOwnPropertySymbols) {
  9. var symbols = Object.getOwnPropertySymbols(object);
  10. enumerableOnly && (symbols = symbols.filter(function (sym) {
  11. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  12. })), keys.push.apply(keys, symbols);
  13. }
  14. return keys;
  15. }
  16. function _objectSpread(target) {
  17. for (var i = 1; i < arguments.length; i++) {
  18. var source = null != arguments[i] ? arguments[i] : {};
  19. i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
  20. _defineProperty(target, key, source[key]);
  21. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
  22. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  23. });
  24. }
  25. return target;
  26. }
  27. function _defineProperty(obj, key, value) {
  28. if (key in obj) {
  29. Object.defineProperty(obj, key, {
  30. value: value,
  31. enumerable: true,
  32. configurable: true,
  33. writable: true
  34. });
  35. } else {
  36. obj[key] = value;
  37. }
  38. return obj;
  39. }
  40. /**
  41. * Automatically generated code, via genSolanaAPI.js
  42. * Do not modify manually
  43. */
  44. const axios = require('axios');
  45. class SolanaApi {
  46. // URL will be changed when api is deployed
  47. static initialize({
  48. apiKey,
  49. serverUrl,
  50. Moralis = null
  51. }) {
  52. if (!serverUrl && !apiKey) {
  53. throw new Error('SolanaApi.initialize failed: initialize with apiKey or serverUrl');
  54. }
  55. if (apiKey) this.apiKey = apiKey;
  56. if (serverUrl) this.serverUrl = serverUrl;
  57. this.Moralis = Moralis;
  58. }
  59. static getBody(params, bodyParams) {
  60. if (!params || !bodyParams || !bodyParams.length) {
  61. return undefined;
  62. }
  63. let body = {};
  64. bodyParams.forEach(({
  65. key,
  66. type,
  67. required
  68. }) => {
  69. if (params[key] === undefined) {
  70. if (required) throw new Error(`param ${key} is required!`);
  71. } else if (type === this.BodyParamTypes.setBody) {
  72. body = params[key];
  73. } else {
  74. body[key] = params[key];
  75. } // remove the param so it doesn't also get added as a query param
  76. delete params[key];
  77. });
  78. return body;
  79. }
  80. static getParameterizedUrl(url, params) {
  81. if (!Object.keys(params).length) return url; // find url params, they start with :
  82. const requiredParams = url.split('/').filter(s => s && s.includes(':'));
  83. if (!requiredParams.length) return url;
  84. let parameterizedUrl = url;
  85. requiredParams.forEach(p => {
  86. // strip the : and replace with param value
  87. const key = p.substr(1);
  88. const value = params[key];
  89. if (!value) {
  90. throw new Error(`required param ${key} not provided`);
  91. }
  92. parameterizedUrl = parameterizedUrl.replace(p, value); // remove required param from param list
  93. // so it doesn't become part of the query params
  94. delete params[key];
  95. });
  96. return parameterizedUrl;
  97. }
  98. static getApiRateLimitInfo(headers) {
  99. return {
  100. 'x-rate-limit-limit': headers['x-rate-limit-limit'],
  101. 'x-rate-limit-remaining-ttl': headers['x-rate-limit-remaining-ttl'],
  102. 'x-rate-limit-used': headers['x-rate-limit-used'],
  103. 'x-rate-limit-remaining-ip-ttl': headers['x-rate-limit-remaining-ip-ttl'],
  104. 'x-rate-limit-ip-used': headers['x-rate-limit-ip-used']
  105. };
  106. }
  107. static getErrorMessage(error, url) {
  108. var _error$response, _error$response$data;
  109. return (error === null || error === void 0 ? void 0 : (_error$response = error.response) === null || _error$response === void 0 ? void 0 : (_error$response$data = _error$response.data) === null || _error$response$data === void 0 ? void 0 : _error$response$data.message) || (error === null || error === void 0 ? void 0 : error.message) || (error === null || error === void 0 ? void 0 : error.toString()) || `Solana API error while calling ${url}`;
  110. }
  111. static async fetch({
  112. endpoint,
  113. params: providedParams
  114. }) {
  115. // Make a shallow copy to prevent modification of original params
  116. const params = _objectSpread({}, providedParams);
  117. if (this.Moralis) {
  118. const {
  119. User
  120. } = this.Moralis;
  121. const user = User.current();
  122. if (!params.address) {
  123. if (user) {
  124. params.address = user.get('solAddress');
  125. }
  126. }
  127. }
  128. if (!params.network) params.network = 'mainnet';
  129. if (!params.responseType) params.responseType = 'native';
  130. if (!this.apiKey) {
  131. return this.fetchFromServer(endpoint.name, params);
  132. }
  133. return this.fetchFromApi(endpoint, params);
  134. }
  135. static async fetchFromApi(endpoint, params) {
  136. const {
  137. method = 'GET',
  138. url,
  139. bodyParams
  140. } = endpoint;
  141. try {
  142. const parameterizedUrl = this.getParameterizedUrl(url, params);
  143. const body = this.getBody(params, bodyParams);
  144. const response = await axios(this.baseURL + parameterizedUrl, {
  145. params,
  146. method,
  147. body,
  148. headers: {
  149. Accept: 'application/json',
  150. 'Content-Type': 'application/json',
  151. 'x-api-key': this.apiKey
  152. }
  153. }); // Perform type regularization before return depending on response type option
  154. return response.data;
  155. } catch (error) {
  156. const {
  157. status,
  158. headers,
  159. data
  160. } = error.response;
  161. let msg;
  162. if (status === 429) {
  163. msg = `This Moralis Server is rate-limited because of the plan restrictions. See the details about the current rate and throttle limits: ${JSON.stringify(this.getApiRateLimitInfo(headers))}`;
  164. } else {
  165. msg = this.getApiErrorMessage(error, url);
  166. }
  167. throw new Error(msg);
  168. }
  169. }
  170. static async fetchFromServer(name, options) {
  171. if (!this.serverUrl) {
  172. throw new Error('SolanaAPI not initialized, run Moralis.start() first');
  173. }
  174. try {
  175. const http = axios.create({
  176. baseURL: this.serverUrl
  177. });
  178. const user = this.Moralis.User.current();
  179. if (user) {
  180. options._SessionToken = user.attributes.sessionToken;
  181. options._ApplicationId = this.Moralis.applicationId;
  182. }
  183. const response = await http.post(`/functions/sol-${name}`, options, {
  184. headers: {
  185. Accept: 'application/json',
  186. 'Content-Type': 'application/json'
  187. }
  188. });
  189. return response.data.result;
  190. } catch (error) {
  191. var _error$response2, _error$response2$data;
  192. if ((_error$response2 = error.response) !== null && _error$response2 !== void 0 && (_error$response2$data = _error$response2.data) !== null && _error$response2$data !== void 0 && _error$response2$data.error) {
  193. throw new Error(error.response.data.error);
  194. }
  195. throw error;
  196. }
  197. }
  198. }
  199. _defineProperty(SolanaApi, "baseURL", 'https://solana-gateway.moralis.io');
  200. _defineProperty(SolanaApi, "BodyParamTypes", {
  201. setBody: 'set body',
  202. property: 'property'
  203. });
  204. _defineProperty(SolanaApi, "account", {
  205. balance: async (options = {}) => SolanaApi.fetch({
  206. endpoint: {
  207. "method": "GET",
  208. "group": "account",
  209. "name": "balance",
  210. "url": "/account/:network/:address/balance"
  211. },
  212. params: options
  213. }),
  214. getSPL: async (options = {}) => SolanaApi.fetch({
  215. endpoint: {
  216. "method": "GET",
  217. "group": "account",
  218. "name": "getSPL",
  219. "url": "/account/:network/:address/tokens"
  220. },
  221. params: options
  222. }),
  223. getNFTs: async (options = {}) => SolanaApi.fetch({
  224. endpoint: {
  225. "method": "GET",
  226. "group": "account",
  227. "name": "getNFTs",
  228. "url": "/account/:network/:address/nft"
  229. },
  230. params: options
  231. }),
  232. getPortfolio: async (options = {}) => SolanaApi.fetch({
  233. endpoint: {
  234. "method": "GET",
  235. "group": "account",
  236. "name": "getPortfolio",
  237. "url": "/account/:network/:address/portfolio"
  238. },
  239. params: options
  240. })
  241. });
  242. _defineProperty(SolanaApi, "nft", {
  243. getNFTMetadata: async (options = {}) => SolanaApi.fetch({
  244. endpoint: {
  245. "method": "GET",
  246. "group": "nft",
  247. "name": "getNFTMetadata",
  248. "url": "/nft/:network/:address/metadata"
  249. },
  250. params: options
  251. })
  252. });
  253. var _default = SolanaApi;
  254. exports.default = _default;