@tetherto/wdk-protocol-fiat-moonpay 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.editorconfig +11 -0
- package/LICENSE +176 -0
- package/README.md +210 -0
- package/bare.js +21 -0
- package/index.js +30 -0
- package/package.json +59 -0
- package/src/moonpay-protocol.js +790 -0
- package/types/index.d.ts +14 -0
- package/types/src/moonpay-protocol.d.ts +928 -0
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
// Copyright 2024 Tether Operations Limited
|
|
2
|
+
//
|
|
3
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
// you may not use this file except in compliance with the License.
|
|
5
|
+
// You may obtain a copy of the License at
|
|
6
|
+
//
|
|
7
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
//
|
|
9
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
// See the License for the specific language governing permissions and
|
|
13
|
+
// limitations under the License.
|
|
14
|
+
|
|
15
|
+
'use strict'
|
|
16
|
+
|
|
17
|
+
import { MoonPay } from '@moonpay/moonpay-node'
|
|
18
|
+
import { FiatProtocol } from '@tetherto/wdk-wallet/protocols'
|
|
19
|
+
import BigNumber from 'bignumber.js'
|
|
20
|
+
|
|
21
|
+
/** @typedef {import('@tetherto/wdk-wallet').IWalletAccount} IWalletAccount */
|
|
22
|
+
/** @typedef {import('@tetherto/wdk-wallet').IWalletAccountReadOnly} IWalletAccountReadOnly */
|
|
23
|
+
|
|
24
|
+
/** @typedef {import("@tetherto/wdk-wallet/protocols").BuyOptions} BuyOptions */
|
|
25
|
+
/** @typedef {import("@tetherto/wdk-wallet/protocols").BuyResult} BuyResult */
|
|
26
|
+
|
|
27
|
+
/** @typedef {import("@tetherto/wdk-wallet/protocols").SellOptions} SellOptions */
|
|
28
|
+
/** @typedef {import("@tetherto/wdk-wallet/protocols").SellCommonOptions} SellCommonOptions */
|
|
29
|
+
/** @typedef {import("@tetherto/wdk-wallet/protocols").SellExactCryptoAmountOptions} SellExactCryptoAmountOptions */
|
|
30
|
+
/** @typedef {import("@tetherto/wdk-wallet/protocols").SellResult} SellResult */
|
|
31
|
+
|
|
32
|
+
/** @typedef {import('@tetherto/wdk-wallet/protocols').FiatQuote} FiatQuote */
|
|
33
|
+
|
|
34
|
+
/** @typedef {import('@tetherto/wdk-wallet/protocols').FiatTransactionStatus} FiatTransactionStatus */
|
|
35
|
+
/** @typedef {import('@tetherto/wdk-wallet/protocols').FiatTransactionDetail} FiatTransactionDetail */
|
|
36
|
+
|
|
37
|
+
/** @typedef {import('@tetherto/wdk-wallet/protocols').SupportedCountry} SupportedCountry */
|
|
38
|
+
/** @typedef {import('@tetherto/wdk-wallet/protocols').SupportedFiatCurrency} SupportedFiatCurrency */
|
|
39
|
+
/** @typedef {import('@tetherto/wdk-wallet/protocols').SupportedCryptoAsset} SupportedCryptoAsset */
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @typedef {Object} MoonPayWidgetUiParams
|
|
43
|
+
* @property {string} [colorCode] - The hexadecimal color code for the widget's main color.
|
|
44
|
+
* @property {'dark' | 'light'} [theme] - The default appearance for the widget.
|
|
45
|
+
* @property {string} [themeId] - The ID of the theme created for your application or website.
|
|
46
|
+
* @property {string} [language] - The ISO 639-1 standard language code for the widget.
|
|
47
|
+
* @property {boolean} [showAllCurrencies] - If true, shows all cryptocurrencies enabled on your account.
|
|
48
|
+
* @property {string} [showOnlyCurrencies] - A comma-separated list of currency codes to display.
|
|
49
|
+
* @property {boolean} [showWalletAddressForm] - If true, shows the wallet address form even if an address is pre-filled.
|
|
50
|
+
* @property {string} [redirectURL] - A URL to redirect the customer to after the flow is complete.
|
|
51
|
+
* @property {string} [unsupportedRegionRedirectUrl] - A URL to redirect the customer to if they are from an unsupported region.
|
|
52
|
+
* @property {boolean} [skipUnsupportedRegionScreen] - If true, skips the unsupported region screen and redirects immediately.
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @typedef {Object} MoonPayWidgetUiBuyParams
|
|
57
|
+
* @property {string} [defaultCurrencyCode] - The code of the cryptocurrency you would prefer the customer to purchase. The customer can still select another currency. If both currencyCode and defaultCurrencyCode are passed, currencyCode will take precedence.
|
|
58
|
+
* @property {string} [walletAddress] - The cryptocurrency wallet address the purchased funds will be sent to. If you pass a valid wallet address the customer won't be prompted to enter one.
|
|
59
|
+
* @property {string} [walletAddressTag] - The secondary cryptocurrency wallet address identifier/memo for coins such as EOS, XLM, XRP and XMR. This parameter will be skipped if walletAddress or currencyCode is not passed.
|
|
60
|
+
* @property {string} [walletAddresses] - A JSON string representing the wallet addresses you want to use for multiple cryptocurrencies. If the customer selects a cryptocurrency for which you have passed a valid wallet address, the customer won't be prompted to enter one. The currency code must be lowercase.
|
|
61
|
+
* @property {string} [walletAddressTags] - A JSON string representing the wallet address tags you want to use for various cryptocurrencies. An example with EOS and XRP wallet address tags: {"eos":"myeostag","xrp":"0123456789"}.
|
|
62
|
+
* @property {string} [contractAddress] - The contract address of the token you want pre-selected for the user in the widget. [Only supported for DeFi Buy integrations.]
|
|
63
|
+
* @property {string} [networkCode] - Defines the network where the token contract exists (e.g., solana, ethereum). Must match the blockchain where the token contract is deployed. [Only supported for DeFi Buy integrations.]
|
|
64
|
+
* @property {boolean} [lockAmount] - Set this parameter to true to lock the baseCurrencyAmount set for the customer and prevent them from modifying it. This parameter will be skipped if baseCurrencyAmount is not passed.
|
|
65
|
+
* @property {string} [email] - The customer's email address. If you pass a valid email address, the customer won't be prompted to enter one.
|
|
66
|
+
* @property {string} [externalTransactionId] - An identifier you would like to associate with the transaction. This identifier will be present whenever we pass you transaction data.
|
|
67
|
+
* @property {string} [externalCustomerId] - An identifier you would like to associate with the customer. This identifier will be present whenever we pass you customer data, allowing you to match our data with your own existing customer data.
|
|
68
|
+
* @property {string} [paymentMethod] - Pre-select the payment method you want the customer to use.
|
|
69
|
+
*/
|
|
70
|
+
|
|
71
|
+
/** @typedef {MoonPayWidgetUiParams & MoonPayWidgetUiBuyParams } MoonPayBuyParams */
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* @typedef {Object} MoonPayWidgetUiSellParams
|
|
75
|
+
* @property {string} [defaultBaseCurrencyCode] - The code of the cryptocurrency you would prefer the customer to sell. If you pass a defaultBaseCurrencyCode, the currency will be selected by default, but the customer will still be able to select another currency.
|
|
76
|
+
* @property {string} [refundWalletAddresses] - A JSON string representing the wallet addresses you want to use for various cryptocurrencies in case we have to issue a refund. An example with BTC and BCH wallet addresses: {"btc": "tb1qst9rvjnhym6kwmdkwgfs4h5dtp7cau5346jp9x", "bch": "bchtest:qraax8trdwct02968swqf4mpq3y5msqp8y7tmalm77"}
|
|
77
|
+
* @property {boolean} [lockAmount] - Set this parameter to true to lock the baseCurrencyAmount set for the customer and prevent them from modifying it. This parameter will be skipped if baseCurrencyAmount is not passed.
|
|
78
|
+
* @property {string} [email] - The customer's email address. If you pass a valid email address, the customer won't be prompted to enter one.
|
|
79
|
+
* @property {string} [externalTransactionId] - An identifier you would like to associate with the transaction. This identifier will be present whenever we pass you transaction data.
|
|
80
|
+
* @property {string} [externalCustomerId] - An identifier you would like to associate with the customer. This identifier will be present whenever we pass you customer data, allowing you to match our data with your own existing customer data.
|
|
81
|
+
* @property {string} [paymentMethod] - Pre-select the payout method you want the customer to use.
|
|
82
|
+
*/
|
|
83
|
+
|
|
84
|
+
/** @typedef {MoonPayWidgetUiParams & MoonPayWidgetUiSellParams } MoonPaySellParams */
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @typedef {Object} MoonPayQuoteBuyParams
|
|
88
|
+
* @property {number} [extraFeePercentage] - A positive integer representing your extra fee percentage for the transaction. The minimum is 0 and the maximum is 10. If you don't provide it, we'll use the default value set to your account.
|
|
89
|
+
* @property {string} [paymentMethod] - The transaction's payment method.
|
|
90
|
+
* @property {boolean} [areFeesIncluded] - A boolean indicating whether baseCurrencyAmount should include extra fees. Defaults to false.
|
|
91
|
+
* @property {string} [walletAddress] - Wallet address of the customer who requested the quote.
|
|
92
|
+
*/
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* @typedef {Object} MoonPayQuoteSellParams
|
|
96
|
+
* @property {number} [extraFeePercentage] - A positive integer representing your extra fee percentage for the transaction. The minimum is 0 and the maximum is 10. If you don't provide it, we'll use the default value set to your account.
|
|
97
|
+
* @property {string} [payoutMethod] - The transaction's payment method.
|
|
98
|
+
*/
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* @typedef {Object} MoonPayBankDepositInfo
|
|
102
|
+
* @property {string | null} iban - The IBAN of the bank account.
|
|
103
|
+
* @property {string | null} bic - The BIC of the bank account.
|
|
104
|
+
* @property {string | null} accountNumber - The account number of the bank account.
|
|
105
|
+
* @property {string | null} sortCode - The sort code of the bank account.
|
|
106
|
+
* @property {string | null} bankName - The name of the bank.
|
|
107
|
+
* @property {string | null} bankAddress - The address of the bank.
|
|
108
|
+
* @property {string} accountName - The account name of the bank account.
|
|
109
|
+
* @property {string} accountAddress - The address of the bank account.
|
|
110
|
+
*/
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* @typedef {Object} MoonPayFiatCurrencyDetails
|
|
114
|
+
* @property {string} id - Unique identifier for the currency.
|
|
115
|
+
* @property {string} createdAt - Time at which the object was created. Returned as an ISO 8601 string.
|
|
116
|
+
* @property {string} updatedAt - Time at which the object was last updated. Returned as an ISO 8601 string.
|
|
117
|
+
* @property {'fiat'} type - Always 'fiat'.
|
|
118
|
+
* @property {string} name - The currency's name.
|
|
119
|
+
* @property {string} code - The currency's code.
|
|
120
|
+
* @property {number} precision - The currency's precision (number of digits after decimal point).
|
|
121
|
+
* @property {number | null} decimals - The currency's decimals.
|
|
122
|
+
* @property {number | null} minBuyAmount - Represents the minimum transaction buy amount when using this currency as a base currency.
|
|
123
|
+
* @property {number | null} maxBuyAmount - Represents the maximum transaction buy amount when using this currency as a base currency.
|
|
124
|
+
* @property {boolean} isSellSupported - Whether sales for this currency are supported.
|
|
125
|
+
*/
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* @typedef {Object} MoonPayCryptoCurrencyDetails
|
|
129
|
+
* @property {string} id - Unique identifier for the currency.
|
|
130
|
+
* @property {string} createdAt - Time at which the object was created. Returned as an ISO 8601 string.
|
|
131
|
+
* @property {string} updatedAt - Time at which the object was last updated. Returned as an ISO 8601 string.
|
|
132
|
+
* @property {'crypto'} type - Always 'crypto'.
|
|
133
|
+
* @property {string} name - The currency's name.
|
|
134
|
+
* @property {string} code - The currency's code.
|
|
135
|
+
* @property {number} precision - The currency's precision (number of digits after decimal point).
|
|
136
|
+
* @property {number} decimals - The currency's decimals.
|
|
137
|
+
* @property {number | null} minBuyAmount - Represents the minimum amount of cryptocurrency you can buy.
|
|
138
|
+
* @property {number | null} maxBuyAmount - Represents the maximum amount of cryptocurrency you can buy.
|
|
139
|
+
* @property {number | null} minSellAmount - The minimum amount of cryptocurrency you can sell.
|
|
140
|
+
* @property {number | null} maxSellAmount - The maximum amount of cryptocurrency you can sell.
|
|
141
|
+
* @property {string} addressRegex - A regular expression which you can test against your end user's wallet addresses.
|
|
142
|
+
* @property {string} testnetAddressRegex - A regular expression which you can test against your end user's testnet wallet addresses.
|
|
143
|
+
* @property {boolean} supportsAddressTag - Whether the currency supports address tags.
|
|
144
|
+
* @property {string | null} addressTagRegex - A regular expression which you can test against a wallet address tag. Defined only if the currency supports address tags.
|
|
145
|
+
* @property {boolean} supportsTestMode - Whether the currency supports test mode.
|
|
146
|
+
* @property {boolean} isSuspended - Whether purchases for this currency are suspended.
|
|
147
|
+
* @property {boolean} isSupportedInUs - Whether purchases for this currency are supported in the US.
|
|
148
|
+
* @property {boolean} isSellSupported - Whether sales for this currency are supported.
|
|
149
|
+
* @property {Array<string>} notAllowedUSStates - A list with all the US states for this currency that are not supported.
|
|
150
|
+
* @property {Array<string>} notAllowedCountries - A list with all the ISO 3166-1 alpha-2 country codes for this currency that are not supported.
|
|
151
|
+
* @property {object} metadata - Additional metadata for the currency.
|
|
152
|
+
* @property {string | null} metadata.contractAddress - Unique contract address where the token smart contract is hosted.
|
|
153
|
+
* @property {string | null} metadata.chainId - ID used to identify different EVM compatible chains.
|
|
154
|
+
* @property {string} metadata.networkCode - Name of the cryptocurrency.
|
|
155
|
+
*/
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* @typedef {Object} MoonPayBuyTransactionStage
|
|
159
|
+
* @property {'stage_one_ordering' | 'stage_two_verification' | 'stage_three_processing' | 'stage_four_delivery'} stage - Stage type.
|
|
160
|
+
* @property {'not_started' | 'in_progress' | 'success' | 'failed'} status - Stage status.
|
|
161
|
+
* @property {string | null} failureReason - Possible values for failure reason.
|
|
162
|
+
* @property {Array<{type: string, url: string}>} actions - An array of actions required for the stage.
|
|
163
|
+
*/
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Type definition for the status of a MoonPay transaction.
|
|
167
|
+
* @typedef {'waitingForDeposit' | 'pending' | 'failed' | 'completed'} MoonPayTransactionStatus
|
|
168
|
+
*/
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* @typedef {Object} MoonPayBuyTransaction
|
|
172
|
+
* @property {string} id - Unique identifier for the object.
|
|
173
|
+
* @property {string} createdAt - Time at which the object was created. Returned as an ISO 8601 string.
|
|
174
|
+
* @property {string} updatedAt - Time at which the object was last updated. Returned as an ISO 8601 string.
|
|
175
|
+
* @property {number} baseCurrencyAmount - A positive number representing how much the customer wants to sell.
|
|
176
|
+
* @property {number} quoteCurrencyAmount - A positive number representing the amount of cryptocurrency the customer will receive.
|
|
177
|
+
* @property {number} feeAmount - A positive number representing the fee for the transaction.
|
|
178
|
+
* @property {number} extraFeeAmount - A positive number representing your extra fee for the transaction.
|
|
179
|
+
* @property {string} paymentMethod - The transaction's payout method.
|
|
180
|
+
* @property {number} networkFeeAmount - The network fee for the transaction.
|
|
181
|
+
* @property {boolean} areFeesIncluded - A boolean indicating whether baseCurrencyAmount includes or excludes the feeAmount, extraFeeAmount and networkFeeAmount.
|
|
182
|
+
* @property {MoonPayTransactionStatus} status - The transaction's status.
|
|
183
|
+
* @property {string | null} failureReason - The transaction's failure reason. Set when transaction's status is failed.
|
|
184
|
+
* @property {string} walletAddress - The cryptocurrency wallet address the purchased funds will be sent to.
|
|
185
|
+
* @property {string | null} walletAddressTag - The secondary cryptocurrency wallet address identifier for coins such as EOS, XRP and XMR.
|
|
186
|
+
* @property {string | null} cryptoTransactionId - The cryptocurrency transaction identifier representing the transfer to the customer's wallet. Set when the withdrawal has been executed.
|
|
187
|
+
* @property {string | null} redirectUrl - The URL provided to you, when required, to which to redirect the customer as part of a redirect authentication flow.
|
|
188
|
+
* @property {string} returnUrl - The URL the customer is returned to after they authenticate or cancel their payment on the payment method's app or site. If you are using our widget implementation, this is always our transaction tracker page, which provides the customer with real-time information about their transaction.
|
|
189
|
+
* @property {string | null} widgetRedirectUrl - An optional URL used in a widget implementation. It is passed to us by you in the query parameters, and we include it as a link on the transaction tracker page.
|
|
190
|
+
* @property {number} eurRate - The exchange rate between the transaction's base currency and Euro at the time of the transaction.
|
|
191
|
+
* @property {number} usdRate - The exchange rate between the transaction's base currency and US Dollar at the time of the transaction.
|
|
192
|
+
* @property {number} gbpRate - The exchange rate between the transaction's base currency and British Pound at the time of the transaction.
|
|
193
|
+
* @property {MoonPayBankDepositInfo | null} bankDepositInformation - Information about the bank deposit.
|
|
194
|
+
* @property {string | null} bankTransferReference - For bank transfer transactions, the reference code the customer should cite when making the transfer.
|
|
195
|
+
* @property {string} currencyId - The identifier of the cryptocurrency the customer wants to purchase.
|
|
196
|
+
* @property {MoonPayCryptoCurrencyDetails} currency - Details of the crypto currency.
|
|
197
|
+
* @property {string} baseCurrencyId - The identifier of the fiat currency the customer wants to use for the transaction.
|
|
198
|
+
* @property {MoonPayFiatCurrencyDetails} baseCurrency - Details of the fiat currency.
|
|
199
|
+
* @property {string} customerId - The identifier of the customer the transaction is associated with.
|
|
200
|
+
* @property {string | null} cardId - For token or card transactions, the identifier of the payment card used for this transaction.
|
|
201
|
+
* @property {string | null} bankAccountId - For bank transfer transactions, the identifier of the bank account used for this transaction.
|
|
202
|
+
* @property {string | null} externalCustomerId - An identifier associated with the customer, provided by you.
|
|
203
|
+
* @property {string | null} externalTransactionId - An identifier associated with the transaction, provided by you.
|
|
204
|
+
* @property {string} country - The customer's country. Returned as an ISO 3166-1 alpha-3 code.
|
|
205
|
+
* @property {string | null} state - The customer's state, if the customer is from the USA. Returned as a two-letter code.
|
|
206
|
+
* @property {string | null} cardType - The customer's state, if the customer is from the USA. Returned as a two-letter code.
|
|
207
|
+
* @property {string} cardPaymentType - The customer's state, if the customer is from the USA. Returned as a two-letter code.
|
|
208
|
+
* @property {Array<MoonPayBuyTransactionStage>} stages - An array of four objects, each representing one of the four stages of the purchase process.
|
|
209
|
+
*/
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* @typedef {Object} MoonPaySellTransactionStage
|
|
213
|
+
* @property {'sell_stage_one_verification' | 'sell_stage_two_waiting_for_deposit' | 'sell_stage_three_processing' | 'sell_stage_four_withdrawal'} stage - Stage type.
|
|
214
|
+
* @property {'not_started' | 'in_progress' | 'success' | 'failed'} status - Stage status.
|
|
215
|
+
* @property {string | null} failureReason - Possible values for failure reason.
|
|
216
|
+
* @property {Array<{type: string, url: string}>} actions - An array of actions required for the stage.
|
|
217
|
+
*/
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* @typedef {Object} MoonPaySellTransaction
|
|
221
|
+
* @property {string} id - Unique identifier for the object.
|
|
222
|
+
* @property {string} createdAt - Time at which the object was created. Returned as an ISO 8601 string.
|
|
223
|
+
* @property {string} updatedAt - Time at which the object was last updated. Returned as an ISO 8601 string.
|
|
224
|
+
* @property {number} baseCurrencyAmount - A positive number representing how much the customer wants to sell.
|
|
225
|
+
* @property {number} quoteCurrencyAmount - A positive number representing the amount of cryptocurrency the customer will receive. Set when the purchase of cryptocurrency has been executed.
|
|
226
|
+
* @property {number} feeAmount - A positive number representing the fee for the transaction.
|
|
227
|
+
* @property {number} extraFeeAmount - A positive number representing your extra fee for the transaction.
|
|
228
|
+
* @property {MoonPayTransactionStatus} status - The transaction's status.
|
|
229
|
+
* @property {string | null} failureReason - The transaction's failure reason. Set when transaction's status is failed.
|
|
230
|
+
* @property {string} refundWalletAddress - A wallet address at which the customer can receive cryptocurrency. In case we cannot process the sale of the customer's cryptocurrency, we will return the cryptocurrency to this wallet address. Might be empty
|
|
231
|
+
* @property {string | null} depositHash - The cryptocurrency transaction identifier representing the transfer from the customer's wallet to MoonPay's wallet. Set when the deposit has been executed and received.
|
|
232
|
+
* @property {string | null} widgetRedirectUrl - An optional URL used in a widget implementation. It is passed to us by you in the query parameters, and we include it as a link on the transaction tracker page.
|
|
233
|
+
* @property {string} payoutMethod - The transaction's payout method.
|
|
234
|
+
* @property {number} eurRate - The exchange rate between the transaction's base currency and Euro at the time of the transaction.
|
|
235
|
+
* @property {number} usdRate - The exchange rate between the transaction's base currency and US Dollar at the time of the transaction.
|
|
236
|
+
* @property {number} gbpRate - The exchange rate between the transaction's base currency and British Pound at the time of the transaction.
|
|
237
|
+
* @property {string} quoteCurrencyId - The identifier of the fiat the customer wants to get.
|
|
238
|
+
* @property {string} baseCurrencyId - The identifier of the crypto currency the customer wants to sell.
|
|
239
|
+
* @property {string} customerId - The identifier of the customer the transaction is associated with.
|
|
240
|
+
* @property {string | null} bankAccountId - The identifier of the bank account used for this transaction.
|
|
241
|
+
* @property {string | null} externalCustomerId - An identifier associated with the customer, provided by you.
|
|
242
|
+
* @property {string | null} externalTransactionId - An identifier associated with the transaction, provided by you.
|
|
243
|
+
* @property {Array<MoonPaySellTransactionStage>} stages - An array of objects, each representing one of the stages of the sell process.
|
|
244
|
+
* @property {MoonPayCryptoCurrencyDetails} baseCurrency - Details of the crypto currency.
|
|
245
|
+
* @property {MoonPayFiatCurrencyDetails} quoteCurrency - Details of the fiat currency.
|
|
246
|
+
*/
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* @typedef {Object} MoonPayCountryDetail
|
|
250
|
+
* @property {string} alpha2 - The country's ISO 3166-1 alpha-2 code.
|
|
251
|
+
* @property {string} alpha3 - The country's ISO 3166-1 alpha-3 code.
|
|
252
|
+
* @property {boolean} isAllowed - Whether residents of this country can use the service.
|
|
253
|
+
* @property {boolean} isBuyAllowed - Whether residents of this country can buy cryptocurrencies.
|
|
254
|
+
* @property {boolean} isSellAllowed - Whether residents of this country can sell cryptocurrencies.
|
|
255
|
+
* @property {string} name - The country's name.
|
|
256
|
+
* @property {string[]} supportedDocuments - A list of supported identity documents for the country.
|
|
257
|
+
*/
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* @typedef {Object} MoonPayBuyQuoteMetadata
|
|
261
|
+
* @property {string} accountId - ID of your business account
|
|
262
|
+
* @property {MoonPayFiatCurrencyDetails} baseCurrency - The fiat currency the customer wants to use for the transaction.
|
|
263
|
+
* @property {string} baseCurrencyCode
|
|
264
|
+
* @property {number} baseCurrencyAmount - A positive number representing how much the customer wants to spend. The minimum amount is 20.
|
|
265
|
+
* @property {MoonPayCryptoCurrencyDetails} quoteCurrency - The cryptocurrency the customer wants to purchase.
|
|
266
|
+
* @property {string} quoteCurrencyCode
|
|
267
|
+
* @property {number} quoteCurrencyAmount - A positive number representing the amount of cryptocurrency the customer will receive. Set when the purchase of cryptocurrency has been executed.
|
|
268
|
+
* @property {number} quoteCurrencyPrice - The price of the crypto the customer will receive
|
|
269
|
+
* @property {string} paymentMethod - The transaction's payment method.
|
|
270
|
+
* @property {number} feeAmount - A positive number representing the fee for the transaction.
|
|
271
|
+
* @property {number} extraFeePercentage
|
|
272
|
+
* @property {number} extraFeeAmount
|
|
273
|
+
* @property {number} networkFeeAmount - A positive number representing the network fee for the transaction. It is added to baseCurrencyAmount, feeAmount and extraFeeAmount when the customer's card is charged.
|
|
274
|
+
* @property {boolean} networkFeeAmountNonRefundable
|
|
275
|
+
* @property {number} totalAmount
|
|
276
|
+
* @property {string | null} externalId
|
|
277
|
+
* @property {string | null} externalCustomerId
|
|
278
|
+
* @property {string | null} signature - The signature for executing the quote for fixed flow
|
|
279
|
+
* @property {number | null} expiresIn - The time in seconds until the quote expires.
|
|
280
|
+
* @property {string | null} expiresAt - Time at which the quote expires. Returned as an ISO 8601 string.
|
|
281
|
+
*/
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* @typedef {Object} MoonPaySellQuoteMetadata
|
|
285
|
+
* @property {string} quoteCurrencyCode - Fiat currency the customer wants to get.
|
|
286
|
+
* @property {MoonPayFiatCurrencyDetails} quoteCurrency - The fiat currency the customer wants to use for the transaction.
|
|
287
|
+
* @property {string} baseCurrencyCode - Crypto currency the customer wants to sell.
|
|
288
|
+
* @property {MoonPayCryptoCurrencyDetails} baseCurrency - The cryptocurrency the customer wants to sell.
|
|
289
|
+
* @property {number} baseCurrencyAmount - A positive number representing how much the customer wants to sell.
|
|
290
|
+
* @property {number} quoteCurrencyAmount - A positive number representing the amount of cryptocurrency the customer will receive.
|
|
291
|
+
* @property {number} baseCurrencyPrice - The price of the crypto the customer wants to sell
|
|
292
|
+
* @property {number} feeAmount - A positive number representing the fee for the transaction.
|
|
293
|
+
* @property {number} extraFeeAmount - A positive number representing your extra fee for the transaction.
|
|
294
|
+
* @property {string} payoutMethod - The transaction's payout method.
|
|
295
|
+
* @property {string | null} signature - The signature for executing the quote for fixed flow
|
|
296
|
+
* @property {number | null} expiresIn - The time in seconds until the quote expires.
|
|
297
|
+
* @property {string | null} expiresAt - Time at which the quote expires. Returned as an ISO 8601 string.
|
|
298
|
+
*/
|
|
299
|
+
|
|
300
|
+
/** @typedef {FiatTransactionDetail & { metadata: MoonPayBuyTransaction | MoonPaySellTransaction }} MoonPayTransactionDetail */
|
|
301
|
+
|
|
302
|
+
/** @typedef {SupportedCountry & { metadata: MoonPayCountryDetail }} MoonPaySupportedCountry */
|
|
303
|
+
|
|
304
|
+
/** @typedef {SupportedCryptoAsset & { metadata: MoonPayCryptoCurrencyDetails }} MoonPaySupportedCryptoAsset */
|
|
305
|
+
|
|
306
|
+
/** @typedef {SupportedFiatCurrency & { metadata: MoonPayFiatCurrencyDetails }} MoonPaySupportedFiatCurrency */
|
|
307
|
+
|
|
308
|
+
/** @typedef {BuyOptions & { config?: MoonPayBuyParams }} MoonPayBuyOptions */
|
|
309
|
+
|
|
310
|
+
/** @typedef {Omit<BuyOptions, 'recipient'> & { config?: MoonPayQuoteBuyParams }} MoonPayQuoteBuyOptions */
|
|
311
|
+
|
|
312
|
+
/** @typedef {FiatQuote & { metadata: MoonPayBuyQuoteMetadata }} MoonPayBuyQuote */
|
|
313
|
+
|
|
314
|
+
/** @typedef {Omit<SellCommonOptions, 'refundAddress'> & SellExactCryptoAmountOptions & { config?: MoonPayQuoteSellParams }} MoonPayQuoteSellOptions */
|
|
315
|
+
|
|
316
|
+
/** @typedef {FiatQuote & { metadata: MoonPaySellQuoteMetadata }} MoonPaySellQuote */
|
|
317
|
+
|
|
318
|
+
/** @typedef {SellOptions & { config?: MoonPaySellParams }} MoonPaySellOptions */
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* @typedef {Object} MoonPayProtocolConfig
|
|
322
|
+
* @property {string} secretKey - Your secret key. MoonPay determines the environment (sandbox or production) based on this key.
|
|
323
|
+
* @property {string} apiKey - Your publishable API key.
|
|
324
|
+
* @property {number} [cacheTime] - The duration in milliseconds to cache supported currencies.
|
|
325
|
+
*/
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Converts a MoonPay transaction status to a standardized WdkRampTransactionStatus.
|
|
329
|
+
* @param {MoonPayTransactionStatus} moonPayStatus - The status from the MoonPay API.
|
|
330
|
+
* @returns {FiatTransactionStatus} The standardized status.
|
|
331
|
+
*/
|
|
332
|
+
function toWdkStatus (moonPayStatus) {
|
|
333
|
+
switch (moonPayStatus) {
|
|
334
|
+
case 'completed':
|
|
335
|
+
return 'completed'
|
|
336
|
+
case 'failed':
|
|
337
|
+
return 'failed'
|
|
338
|
+
case 'pending':
|
|
339
|
+
case 'waitingForDeposit':
|
|
340
|
+
return 'in_progress'
|
|
341
|
+
default:
|
|
342
|
+
return 'in_progress'
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Gets the decimals for a fiat currency, falling back to precision.
|
|
348
|
+
* @param {MoonPayFiatCurrencyDetails} currencyDetail
|
|
349
|
+
* @returns {number}
|
|
350
|
+
*/
|
|
351
|
+
function getFiatDecimals (currencyDetail) {
|
|
352
|
+
const decimals = currencyDetail.decimals ?? currencyDetail.precision
|
|
353
|
+
|
|
354
|
+
if (typeof decimals !== 'number') {
|
|
355
|
+
throw new Error(`Could not determine decimals for fiat currency: ${currencyDetail.code}`)
|
|
356
|
+
}
|
|
357
|
+
return decimals
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const MOONPAY_API_DOMAIN = 'https://api.moonpay.com/'
|
|
361
|
+
const MOONPAY_CACHE_TIME = 10 * 60 * 1000
|
|
362
|
+
|
|
363
|
+
export default class MoonPayProtocol extends FiatProtocol {
|
|
364
|
+
/**
|
|
365
|
+
* Creates a new interface to interact with the MoonPay protocol without binding it to a wallet account.
|
|
366
|
+
*
|
|
367
|
+
* @overload
|
|
368
|
+
* @param {undefined} account - The wallet account to use to interact with the protocol.
|
|
369
|
+
* @param {MoonPayProtocolConfig} config - The MoonPay protocol configuration.
|
|
370
|
+
*/
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Creates a new read-only interface to interact with the MoonPay protocol.
|
|
374
|
+
*
|
|
375
|
+
* @overload
|
|
376
|
+
* @param {IWalletAccountReadOnly} account - The wallet account to use to interact with the protocol.
|
|
377
|
+
* @param {MoonPayProtocolConfig} config - The MoonPay protocol configuration.
|
|
378
|
+
*/
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Creates a new interface to interact with the MoonPay protocol.
|
|
382
|
+
*
|
|
383
|
+
* @overload
|
|
384
|
+
* @param {IWalletAccount} account - The wallet account to use to interact with the protocol.
|
|
385
|
+
* @param {MoonPayProtocolConfig} config - The MoonPay protocol configuration.
|
|
386
|
+
*/
|
|
387
|
+
constructor (account, { secretKey, apiKey, cacheTime = MOONPAY_CACHE_TIME }) {
|
|
388
|
+
super(account)
|
|
389
|
+
|
|
390
|
+
/** @private */
|
|
391
|
+
this._moonPay = new MoonPay(secretKey)
|
|
392
|
+
|
|
393
|
+
/** @private */
|
|
394
|
+
this._apiKey = apiKey
|
|
395
|
+
|
|
396
|
+
/** @private */
|
|
397
|
+
this._supportedCurrenciesCache = undefined
|
|
398
|
+
|
|
399
|
+
/** @private */
|
|
400
|
+
this._cacheThreshold = cacheTime
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** @private */
|
|
404
|
+
async _getAssetDetails (cryptoAsset, fiatCurrency) {
|
|
405
|
+
const supportedAssets = await this._fetchAndCacheSupportedCurrencies()
|
|
406
|
+
|
|
407
|
+
const cryptoInfo = supportedAssets.find((asset) => asset.code === cryptoAsset)
|
|
408
|
+
const fiatInfo = supportedAssets.find((asset) => asset.code === fiatCurrency)
|
|
409
|
+
|
|
410
|
+
if (!cryptoInfo || !fiatInfo) {
|
|
411
|
+
throw new Error('Cannot find info for cryptoAsset and fiatCurrency')
|
|
412
|
+
}
|
|
413
|
+
return { cryptoInfo, fiatInfo }
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Generates a widget URL for a user to purchase a crypto asset with fiat currency.
|
|
418
|
+
* @override
|
|
419
|
+
* @param {MoonPayBuyOptions} options - The options for the purchase.
|
|
420
|
+
* @returns {Promise<BuyResult>} The URL for the user to complete the purchase.
|
|
421
|
+
*/
|
|
422
|
+
async buy (options) {
|
|
423
|
+
const { cryptoAsset, fiatCurrency, recipient, config } = options
|
|
424
|
+
|
|
425
|
+
const params = {
|
|
426
|
+
...config,
|
|
427
|
+
currencyCode: cryptoAsset,
|
|
428
|
+
baseCurrencyCode: fiatCurrency,
|
|
429
|
+
apiKey: this._apiKey
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const { cryptoInfo, fiatInfo } = await this._getAssetDetails(cryptoAsset, fiatCurrency)
|
|
433
|
+
|
|
434
|
+
const fiatDecimals = getFiatDecimals(fiatInfo)
|
|
435
|
+
|
|
436
|
+
if ('cryptoAmount' in options && 'fiatAmount' in options) {
|
|
437
|
+
throw new Error('\'cryptoAmount\' and \'fiatAmount\' cannot both be provided')
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
if ('cryptoAmount' in options) {
|
|
441
|
+
params.quoteCurrencyAmount = new BigNumber(options.cryptoAmount)
|
|
442
|
+
.shiftedBy(-1 * cryptoInfo.decimals)
|
|
443
|
+
.toFixed(cryptoInfo.precision, 1)
|
|
444
|
+
} else if ('fiatAmount' in options) {
|
|
445
|
+
params.baseCurrencyAmount = new BigNumber(options.fiatAmount)
|
|
446
|
+
.shiftedBy(-1 * fiatDecimals)
|
|
447
|
+
.toFixed(fiatInfo.precision, 1)
|
|
448
|
+
} else {
|
|
449
|
+
throw new Error('Either \'cryptoAmount\' or \'fiatAmount\' must be provided')
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
if (recipient) {
|
|
453
|
+
params.walletAddress = recipient
|
|
454
|
+
} else if (this._account) {
|
|
455
|
+
params.walletAddress = await this._account.getAddress()
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const buyUrl = this._moonPay.url.generate({
|
|
459
|
+
flow: 'buy',
|
|
460
|
+
params
|
|
461
|
+
})
|
|
462
|
+
|
|
463
|
+
return {
|
|
464
|
+
buyUrl
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* Gets a quote for a crypto asset purchase.
|
|
470
|
+
* @override
|
|
471
|
+
* @param {MoonPayQuoteBuyOptions} options - The options for the quote.
|
|
472
|
+
* @returns {Promise<MoonPayBuyQuote>} A quote for the transaction.
|
|
473
|
+
*/
|
|
474
|
+
async quoteBuy (options) {
|
|
475
|
+
const { cryptoAsset, fiatCurrency, config } = options
|
|
476
|
+
|
|
477
|
+
const params = {
|
|
478
|
+
...config,
|
|
479
|
+
baseCurrencyCode: fiatCurrency
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
const { cryptoInfo, fiatInfo } = await this._getAssetDetails(cryptoAsset, fiatCurrency)
|
|
483
|
+
|
|
484
|
+
const fiatDecimals = getFiatDecimals(fiatInfo)
|
|
485
|
+
|
|
486
|
+
if ('cryptoAmount' in options && 'fiatAmount' in options) {
|
|
487
|
+
throw new Error('\'cryptoAmount\' and \'fiatAmount\' cannot both be provided')
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
if ('cryptoAmount' in options) {
|
|
491
|
+
params.quoteCurrencyAmount = new BigNumber(options.cryptoAmount)
|
|
492
|
+
.shiftedBy(-1 * cryptoInfo.decimals)
|
|
493
|
+
.toFixed(cryptoInfo.precision, 1)
|
|
494
|
+
} else if ('fiatAmount' in options) {
|
|
495
|
+
params.baseCurrencyAmount = new BigNumber(options.fiatAmount)
|
|
496
|
+
.shiftedBy(-1 * fiatDecimals)
|
|
497
|
+
.toFixed(fiatInfo.precision, 1)
|
|
498
|
+
} else {
|
|
499
|
+
throw new Error('Either \'cryptoAmount\' or \'fiatAmount\' must be provided')
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const url = new URL(`v3/currencies/${cryptoAsset}/buy_quote`, MOONPAY_API_DOMAIN)
|
|
503
|
+
|
|
504
|
+
url.searchParams.append('apiKey', this._apiKey)
|
|
505
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
506
|
+
if (value !== undefined && value !== null) {
|
|
507
|
+
url.searchParams.append(key, value)
|
|
508
|
+
}
|
|
509
|
+
})
|
|
510
|
+
|
|
511
|
+
const resp = await fetch(url.toString(), {
|
|
512
|
+
headers: { accept: 'application/json' }
|
|
513
|
+
})
|
|
514
|
+
|
|
515
|
+
if (!resp.ok) {
|
|
516
|
+
throw new Error(`Failed to fetch MoonPay buy quote: ${resp.status} ${resp.statusText}`)
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
const quote = await resp.json()
|
|
520
|
+
|
|
521
|
+
const cryptoAmount = new BigNumber(quote.quoteCurrencyAmount).shiftedBy(cryptoInfo.decimals)
|
|
522
|
+
const fiatAmount = new BigNumber(quote.baseCurrencyAmount).shiftedBy(fiatDecimals)
|
|
523
|
+
const totalFee = new BigNumber(quote.feeAmount).plus(quote.extraFeeAmount).plus(quote.networkFeeAmount).shiftedBy(fiatDecimals)
|
|
524
|
+
|
|
525
|
+
return {
|
|
526
|
+
cryptoAmount: BigInt(cryptoAmount.toFixed()),
|
|
527
|
+
fiatAmount: BigInt(fiatAmount.toFixed()),
|
|
528
|
+
fee: BigInt(totalFee.toFixed()),
|
|
529
|
+
rate: quote.quoteCurrencyPrice.toString(),
|
|
530
|
+
metadata: quote
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Gets a quote for a crypto asset sale.
|
|
536
|
+
* @override
|
|
537
|
+
* @param {MoonPayQuoteSellOptions} options - The options for the quote.
|
|
538
|
+
* @returns {Promise<MoonPaySellQuote>} A quote for the transaction.
|
|
539
|
+
*/
|
|
540
|
+
async quoteSell (options) {
|
|
541
|
+
const { cryptoAsset, fiatCurrency, cryptoAmount, config } = options
|
|
542
|
+
|
|
543
|
+
if (cryptoAmount === undefined) {
|
|
544
|
+
throw new Error('\'cryptoAmount\' must be provided')
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
const params = {
|
|
548
|
+
...config,
|
|
549
|
+
quoteCurrencyCode: fiatCurrency
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
const { cryptoInfo, fiatInfo } = await this._getAssetDetails(cryptoAsset, fiatCurrency)
|
|
553
|
+
|
|
554
|
+
const fiatDecimals = getFiatDecimals(fiatInfo)
|
|
555
|
+
|
|
556
|
+
params.baseCurrencyAmount = new BigNumber(cryptoAmount)
|
|
557
|
+
.shiftedBy(-1 * cryptoInfo.decimals)
|
|
558
|
+
.toFixed(cryptoInfo.precision, 1)
|
|
559
|
+
|
|
560
|
+
const url = new URL(`v3/currencies/${cryptoAsset}/sell_quote`, MOONPAY_API_DOMAIN)
|
|
561
|
+
|
|
562
|
+
url.searchParams.append('apiKey', this._apiKey)
|
|
563
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
564
|
+
if (value !== undefined && value !== null) {
|
|
565
|
+
url.searchParams.append(key, value)
|
|
566
|
+
}
|
|
567
|
+
})
|
|
568
|
+
|
|
569
|
+
const resp = await fetch(url.toString(), {
|
|
570
|
+
headers: { accept: 'application/json' }
|
|
571
|
+
})
|
|
572
|
+
|
|
573
|
+
if (!resp.ok) {
|
|
574
|
+
throw new Error(`Failed to fetch MoonPay sell quote: ${resp.status} ${resp.statusText}`)
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
const quote = await resp.json()
|
|
578
|
+
|
|
579
|
+
const quotedCryptoAmount = new BigNumber(quote.baseCurrencyAmount).shiftedBy(cryptoInfo.decimals)
|
|
580
|
+
const quotedFiatAmount = new BigNumber(quote.quoteCurrencyAmount).shiftedBy(fiatDecimals)
|
|
581
|
+
const totalFee = new BigNumber(quote.feeAmount).plus(quote.extraFeeAmount).shiftedBy(fiatDecimals)
|
|
582
|
+
|
|
583
|
+
return {
|
|
584
|
+
cryptoAmount: BigInt(quotedCryptoAmount.toFixed()),
|
|
585
|
+
fiatAmount: BigInt(quotedFiatAmount.toFixed()),
|
|
586
|
+
fee: BigInt(totalFee.toFixed()),
|
|
587
|
+
rate: quote.baseCurrencyPrice.toString(),
|
|
588
|
+
metadata: quote
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Generates a widget URL for a user to sell a crypto asset for fiat currency.
|
|
594
|
+
* @override
|
|
595
|
+
* @param {MoonPaySellOptions} options - The options for the sale.
|
|
596
|
+
* @returns {Promise<SellResult>} The URL for the user to complete the sale.
|
|
597
|
+
*/
|
|
598
|
+
async sell (options) {
|
|
599
|
+
const { cryptoAsset, fiatCurrency, refundAddress, config } = options
|
|
600
|
+
|
|
601
|
+
const params = {
|
|
602
|
+
...config,
|
|
603
|
+
baseCurrencyCode: cryptoAsset,
|
|
604
|
+
quoteCurrencyCode: fiatCurrency,
|
|
605
|
+
apiKey: this._apiKey
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const { cryptoInfo, fiatInfo } = await this._getAssetDetails(cryptoAsset, fiatCurrency)
|
|
609
|
+
|
|
610
|
+
const fiatDecimals = getFiatDecimals(fiatInfo)
|
|
611
|
+
|
|
612
|
+
if ('cryptoAmount' in options && 'fiatAmount' in options) {
|
|
613
|
+
throw new Error('\'cryptoAmount\' and \'fiatAmount\' cannot both be provided')
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
if ('cryptoAmount' in options) {
|
|
617
|
+
params.baseCurrencyAmount = new BigNumber(options.cryptoAmount)
|
|
618
|
+
.shiftedBy(-1 * cryptoInfo.decimals)
|
|
619
|
+
.toFixed(cryptoInfo.precision, 1)
|
|
620
|
+
} else if ('fiatAmount' in options) {
|
|
621
|
+
params.quoteCurrencyAmount = new BigNumber(options.fiatAmount)
|
|
622
|
+
.shiftedBy(-1 * fiatDecimals)
|
|
623
|
+
.toFixed(fiatInfo.precision, 1)
|
|
624
|
+
} else {
|
|
625
|
+
throw new Error('Either \'cryptoAmount\' or \'fiatAmount\' must be provided')
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
if (refundAddress) {
|
|
629
|
+
params.refundWalletAddress = refundAddress
|
|
630
|
+
} else if (this._account) {
|
|
631
|
+
params.refundWalletAddress = await this._account.getAddress()
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
const sellUrl = this._moonPay.url.generate({
|
|
635
|
+
flow: 'sell',
|
|
636
|
+
params
|
|
637
|
+
})
|
|
638
|
+
|
|
639
|
+
return {
|
|
640
|
+
sellUrl
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/**
|
|
645
|
+
* Retrieves the details of a specific transaction from the provider.
|
|
646
|
+
* @override
|
|
647
|
+
* @param {string} txId - The unique identifier of the transaction.
|
|
648
|
+
* @param {'buy' | 'sell'} [direction] - The direction of the transaction.
|
|
649
|
+
* @returns {Promise<MoonPayTransactionDetail>} The transaction details.
|
|
650
|
+
*/
|
|
651
|
+
async getTransactionDetail (txId, direction = 'buy') {
|
|
652
|
+
if (!['buy', 'sell'].includes(direction)) {
|
|
653
|
+
throw new Error('Invalid direction')
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const path = direction === 'buy' ? `v1/transactions/${txId}` : `v3/sell_transactions/${txId}`
|
|
657
|
+
|
|
658
|
+
const url = new URL(path, MOONPAY_API_DOMAIN)
|
|
659
|
+
|
|
660
|
+
url.searchParams.append('apiKey', this._apiKey)
|
|
661
|
+
|
|
662
|
+
const resp = await fetch(url.toString(), {
|
|
663
|
+
headers: {
|
|
664
|
+
accept: 'application/json'
|
|
665
|
+
}
|
|
666
|
+
})
|
|
667
|
+
|
|
668
|
+
if (!resp.ok) {
|
|
669
|
+
throw new Error(`Failed to fetch MoonPay transaction detail: ${resp.status} ${resp.statusText}`)
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
const moonPayTransaction = await resp.json()
|
|
673
|
+
const cryptoAssetId = direction === 'buy' ? moonPayTransaction.currencyId : moonPayTransaction.baseCurrencyId
|
|
674
|
+
const fiatCurrencyId = direction === 'buy' ? moonPayTransaction.baseCurrencyId : moonPayTransaction.quoteCurrencyId
|
|
675
|
+
|
|
676
|
+
return {
|
|
677
|
+
status: toWdkStatus(moonPayTransaction.status),
|
|
678
|
+
cryptoAsset: cryptoAssetId,
|
|
679
|
+
fiatCurrency: fiatCurrencyId,
|
|
680
|
+
metadata: moonPayTransaction
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* Fetches and caches supported currencies from MoonPay.
|
|
686
|
+
* @private
|
|
687
|
+
* @returns {Promise<Array<MoonPayCryptoCurrencyDetails | MoonPayFiatCurrencyDetails>>}
|
|
688
|
+
*/
|
|
689
|
+
async _fetchAndCacheSupportedCurrencies () {
|
|
690
|
+
const now = Date.now()
|
|
691
|
+
|
|
692
|
+
if (!this._supportedCurrenciesCache || (now - this._supportedCurrenciesCache.timestamp >= this._cacheThreshold)) {
|
|
693
|
+
const url = new URL('v3/currencies', MOONPAY_API_DOMAIN)
|
|
694
|
+
url.searchParams.append('apiKey', this._apiKey)
|
|
695
|
+
|
|
696
|
+
const resp = await fetch(url.toString(), {
|
|
697
|
+
headers: { accept: 'application/json' }
|
|
698
|
+
})
|
|
699
|
+
|
|
700
|
+
if (!resp.ok) {
|
|
701
|
+
throw new Error(`Failed to fetch MoonPay supported currencies: ${resp.status} ${resp.statusText}`)
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const data = await resp.json()
|
|
705
|
+
|
|
706
|
+
this._supportedCurrenciesCache = {
|
|
707
|
+
timestamp: now,
|
|
708
|
+
data
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
return this._supportedCurrenciesCache?.data || []
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Retrieves a list of supported crypto assets from the provider.
|
|
717
|
+
* @override
|
|
718
|
+
* @returns {Promise<MoonPaySupportedCryptoAsset[]>} An array of supported crypto assets.
|
|
719
|
+
*/
|
|
720
|
+
async getSupportedCryptoAssets () {
|
|
721
|
+
const allCurrencies = await this._fetchAndCacheSupportedCurrencies()
|
|
722
|
+
|
|
723
|
+
return allCurrencies
|
|
724
|
+
.filter((currency) => currency.type === 'crypto')
|
|
725
|
+
.map((assetDetail) => {
|
|
726
|
+
return {
|
|
727
|
+
code: assetDetail.code,
|
|
728
|
+
decimals: assetDetail.decimals,
|
|
729
|
+
networkCode: assetDetail.metadata.networkCode,
|
|
730
|
+
name: assetDetail.name,
|
|
731
|
+
metadata: assetDetail
|
|
732
|
+
}
|
|
733
|
+
})
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* Retrieves a list of supported fiat currencies from the provider.
|
|
738
|
+
* @override
|
|
739
|
+
* @returns {Promise<MoonPaySupportedFiatCurrency[]>} An array of supported fiat currencies.
|
|
740
|
+
*/
|
|
741
|
+
async getSupportedFiatCurrencies () {
|
|
742
|
+
const allCurrencies = await this._fetchAndCacheSupportedCurrencies()
|
|
743
|
+
|
|
744
|
+
return allCurrencies
|
|
745
|
+
.filter((currency) => currency.type === 'fiat')
|
|
746
|
+
.map((currencyDetail) => ({
|
|
747
|
+
code: currencyDetail.code,
|
|
748
|
+
decimals: getFiatDecimals(currencyDetail),
|
|
749
|
+
name: currencyDetail.name,
|
|
750
|
+
metadata: currencyDetail
|
|
751
|
+
}))
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Retrieves a list of supported countries from the provider.
|
|
756
|
+
* @override
|
|
757
|
+
* @returns {Promise<MoonPaySupportedCountry[]>} An array of supported countries.
|
|
758
|
+
*/
|
|
759
|
+
async getSupportedCountries () {
|
|
760
|
+
const url = new URL('v3/countries', MOONPAY_API_DOMAIN)
|
|
761
|
+
|
|
762
|
+
url.searchParams.append('apiKey', this._apiKey)
|
|
763
|
+
|
|
764
|
+
const resp = await fetch(url.toString(), {
|
|
765
|
+
headers: {
|
|
766
|
+
accept: 'application/json'
|
|
767
|
+
}
|
|
768
|
+
})
|
|
769
|
+
|
|
770
|
+
if (!resp.ok) {
|
|
771
|
+
throw new Error(`Failed to fetch supported countries: ${resp.status} ${resp.statusText}`)
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
const moonPaySupportedCountries = await resp.json()
|
|
775
|
+
|
|
776
|
+
if (!Array.isArray(moonPaySupportedCountries)) {
|
|
777
|
+
throw new Error('Failed to fetch supported countries')
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
return moonPaySupportedCountries.map((countryDetail) => {
|
|
781
|
+
return {
|
|
782
|
+
code: countryDetail.alpha2 || countryDetail.alpha3,
|
|
783
|
+
isBuyAllowed: countryDetail.isBuyAllowed,
|
|
784
|
+
isSellAllowed: countryDetail.isSellAllowed,
|
|
785
|
+
name: countryDetail.name,
|
|
786
|
+
metadata: countryDetail
|
|
787
|
+
}
|
|
788
|
+
})
|
|
789
|
+
}
|
|
790
|
+
}
|