/
fundWallet.ts
339 lines (317 loc) · 10.2 KB
/
fundWallet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import { IncomingMessage } from 'http'
import { request as httpsRequest, RequestOptions } from 'https'
import { isValidClassicAddress } from 'ripple-address-codec'
import type { Client } from '../client'
import { RippledError, XRPLFaucetError } from '../errors'
import {
FaucetWallet,
getFaucetHost,
getDefaultFaucetPath,
} from './defaultFaucets'
import Wallet from '.'
// Interval to check an account balance
const INTERVAL_SECONDS = 1
// Maximum attempts to retrieve a balance
const MAX_ATTEMPTS = 20
/**
* The fundWallet() method is used to send an amount of XRP (usually 1000) to a new (randomly generated)
* or existing XRP Ledger wallet.
*
* @example
*
* Example 1: Fund a randomly generated wallet
* const { Client, Wallet } = require('xrpl')
*
* const client = new Client('wss://s.altnet.rippletest.net:51233')
* await client.connect()
* const { balance, wallet } = await client.fundWallet()
*
* Under the hood, this will use `Wallet.generate()` to create a new random wallet, then ask a testnet faucet
* To send it XRP on ledger to make it a real account. If successful, this will return the new account balance in XRP
* Along with the Wallet object to track the keys for that account. If you'd like, you can also re-fill an existing
* Account by passing in a Wallet you already have.
* ```ts
* const api = new xrpl.Client("wss://s.altnet.rippletest.net:51233")
* await api.connect()
* const { wallet, balance } = await api.fundWallet()
* ```
*
* Example 2: Fund wallet using a custom faucet host and known wallet address
*
* `fundWallet` will try to infer the url of a faucet API from the network your client is connected to.
* There are hardcoded default faucets for popular test networks like testnet and devnet.
* However, if you're working with a newer or more obscure network, you may have to specify the faucetHost
* And faucetPath so `fundWallet` can ask that faucet to fund your wallet.
*
* ```ts
* const newWallet = Wallet.generate()
* const { balance, wallet } = await client.fundWallet(newWallet, {
* amount: '10',
* faucetHost: 'https://custom-faucet.example.com',
* faucetPath: '/accounts'
* })
* console.log(`Sent 10 XRP to wallet: ${address} from the given faucet. Resulting balance: ${balance} XRP`)
* } catch (error) {
* console.error(`Failed to fund wallet: ${error}`)
* }
* }
* ```
*
* @param this - Client.
* @param wallet - An existing XRPL Wallet to fund. If undefined or null, a new Wallet will be created.
* @param options - See below.
* @param options.faucetHost - A custom host for a faucet server. On devnet,
* testnet, AMM devnet, and HooksV2 testnet, `fundWallet` will
* attempt to determine the correct server automatically. In other environments,
* or if you would like to customize the faucet host in devnet or testnet,
* you should provide the host using this option.
* @param options.faucetPath - A custom path for a faucet server. On devnet,
* testnet, AMM devnet, and HooksV2 testnet, `fundWallet` will
* attempt to determine the correct path automatically. In other environments,
* or if you would like to customize the faucet path in devnet or testnet,
* you should provide the path using this option.
* Ex: client.fundWallet(null,{'faucet.altnet.rippletest.net', '/accounts'})
* specifies a request to 'faucet.altnet.rippletest.net/accounts' to fund a new wallet.
* @param options.amount - A custom amount to fund, if undefined or null, the default amount will be 1000.
* @returns A Wallet on the Testnet or Devnet that contains some amount of XRP,
* and that wallet's balance in XRP.
* @throws When either Client isn't connected or unable to fund wallet address.
*/
// eslint-disable-next-line max-lines-per-function -- All lines necessary
async function fundWallet(
this: Client,
wallet?: Wallet | null,
options?: {
faucetHost?: string
faucetPath?: string
amount?: string
},
): Promise<{
wallet: Wallet
balance: number
}> {
if (!this.isConnected()) {
throw new RippledError('Client not connected, cannot call faucet')
}
// Generate a new Wallet if no existing Wallet is provided or its address is invalid to fund
const walletToFund =
wallet && isValidClassicAddress(wallet.classicAddress)
? wallet
: Wallet.generate()
// Create the POST request body
const postBody = Buffer.from(
new TextEncoder().encode(
JSON.stringify({
destination: walletToFund.classicAddress,
xrpAmount: options?.amount,
}),
),
)
let startingBalance = 0
try {
startingBalance = Number(
await this.getXrpBalance(walletToFund.classicAddress),
)
} catch {
/* startingBalance remains '0' */
}
// Options to pass to https.request
const httpOptions = getHTTPOptions(this, postBody, {
hostname: options?.faucetHost,
pathname: options?.faucetPath,
})
return returnPromise(
httpOptions,
this,
startingBalance,
walletToFund,
postBody,
)
}
// eslint-disable-next-line max-params -- Helper function created for organizational purposes
async function returnPromise(
options: RequestOptions,
client: Client,
startingBalance: number,
walletToFund: Wallet,
postBody: Buffer,
): Promise<{
wallet: Wallet
balance: number
}> {
return new Promise((resolve, reject) => {
const request = httpsRequest(options, (response) => {
const chunks: Uint8Array[] = []
response.on('data', (data) => chunks.push(data))
// eslint-disable-next-line @typescript-eslint/no-misused-promises -- not actually misused, different resolve/reject
response.on('end', async () =>
onEnd(
response,
chunks,
client,
startingBalance,
walletToFund,
resolve,
reject,
),
)
})
// POST the body
request.write(postBody)
request.on('error', (error) => {
reject(error)
})
request.end()
})
}
function getHTTPOptions(
client: Client,
postBody: Uint8Array,
options?: {
hostname?: string
pathname?: string
},
): RequestOptions {
const finalHostname = options?.hostname ?? getFaucetHost(client)
const finalPathname = options?.pathname ?? getDefaultFaucetPath(finalHostname)
return {
hostname: finalHostname,
port: 443,
path: finalPathname,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postBody.length,
},
}
}
// eslint-disable-next-line max-params -- Helper function created for organizational purposes
async function onEnd(
response: IncomingMessage,
chunks: Uint8Array[],
client: Client,
startingBalance: number,
walletToFund: Wallet,
resolve: (response: { wallet: Wallet; balance: number }) => void,
reject: (err: ErrorConstructor | Error | unknown) => void,
): Promise<void> {
const body = Buffer.concat(chunks).toString()
// "application/json; charset=utf-8"
if (response.headers['content-type']?.startsWith('application/json')) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- We know this is safe and correct
const faucetWallet: FaucetWallet = JSON.parse(body)
const classicAddress = faucetWallet.account.classicAddress
await processSuccessfulResponse(
client,
classicAddress,
walletToFund,
startingBalance,
resolve,
reject,
)
} else {
reject(
new XRPLFaucetError(
`Content type is not \`application/json\`: ${JSON.stringify({
statusCode: response.statusCode,
contentType: response.headers['content-type'],
body,
})}`,
),
)
}
}
// eslint-disable-next-line max-params, max-lines-per-function -- Only used as a helper function, lines inc due to added balance.
async function processSuccessfulResponse(
client: Client,
classicAddress: string | undefined,
walletToFund: Wallet,
startingBalance: number,
resolve: (response: { wallet: Wallet; balance: number }) => void,
reject: (err: ErrorConstructor | Error | unknown) => void,
): Promise<void> {
if (!classicAddress) {
reject(new XRPLFaucetError(`The faucet account is undefined`))
return
}
try {
// Check at regular interval if the address is enabled on the XRPL and funded
const updatedBalance = await getUpdatedBalance(
client,
classicAddress,
startingBalance,
)
if (updatedBalance > startingBalance) {
resolve({
wallet: walletToFund,
balance: await getUpdatedBalance(
client,
walletToFund.classicAddress,
startingBalance,
),
})
} else {
reject(
new XRPLFaucetError(
`Unable to fund address with faucet after waiting ${
INTERVAL_SECONDS * MAX_ATTEMPTS
} seconds`,
),
)
}
} catch (err) {
if (err instanceof Error) {
reject(new XRPLFaucetError(err.message))
}
reject(err)
}
}
/**
* Check at regular interval if the address is enabled on the XRPL and funded.
*
* @param client - Client.
* @param address - The account address to check.
* @param originalBalance - The initial balance before the funding.
* @returns A Promise boolean.
*/
async function getUpdatedBalance(
client: Client,
address: string,
originalBalance: number,
): Promise<number> {
return new Promise((resolve, reject) => {
let attempts = MAX_ATTEMPTS
// eslint-disable-next-line @typescript-eslint/no-misused-promises -- Not actually misused here, different resolve
const interval = setInterval(async () => {
if (attempts < 0) {
clearInterval(interval)
resolve(originalBalance)
} else {
attempts -= 1
}
try {
let newBalance
try {
newBalance = Number(await client.getXrpBalance(address))
} catch {
/* newBalance remains undefined */
}
if (newBalance > originalBalance) {
clearInterval(interval)
resolve(newBalance)
}
} catch (err) {
clearInterval(interval)
if (err instanceof Error) {
reject(
new XRPLFaucetError(
`Unable to check if the address ${address} balance has increased. Error: ${err.message}`,
),
)
}
reject(err)
}
}, INTERVAL_SECONDS * 1000)
})
}
export default fundWallet