@xrpay/x402 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +191 -2
- package/dist/browser.js +2 -0
- package/dist/client.cjs +1552 -0
- package/dist/client.d.cts +46 -0
- package/dist/client.d.ts +46 -0
- package/dist/client.js +1529 -0
- package/dist/commerce.cjs +1611 -0
- package/dist/commerce.d.cts +99 -0
- package/dist/commerce.d.ts +99 -0
- package/dist/commerce.js +1588 -0
- package/dist/mcp-tools.d.ts +56 -0
- package/dist/mcp.d.ts +1 -0
- package/dist/mcp.js +1749 -0
- package/dist/protocol.cjs +1447 -0
- package/dist/protocol.d.cts +64 -0
- package/dist/protocol.d.ts +64 -0
- package/dist/protocol.js +1424 -0
- package/dist/server.cjs +1772 -0
- package/dist/server.d.cts +62 -0
- package/dist/server.d.ts +62 -0
- package/dist/server.js +1723 -0
- package/examples/buy-digital-product.mjs +44 -0
- package/examples/paid-api.mjs +25 -0
- package/package.json +101 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,1723 @@
|
|
|
1
|
+
// src/server.ts
|
|
2
|
+
import * as crypto2 from "node:crypto";
|
|
3
|
+
import { Client, decode, deriveAddress, hashes, isValidClassicAddress, validate, verifySignature } from "xrpl";
|
|
4
|
+
|
|
5
|
+
// ../../node_modules/bignumber.js/bignumber.mjs
|
|
6
|
+
var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
|
|
7
|
+
var mathceil = Math.ceil;
|
|
8
|
+
var mathfloor = Math.floor;
|
|
9
|
+
var bignumberError = "[BigNumber Error] ";
|
|
10
|
+
var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: ";
|
|
11
|
+
var BASE = 1e14;
|
|
12
|
+
var LOG_BASE = 14;
|
|
13
|
+
var MAX_SAFE_INTEGER = 9007199254740991;
|
|
14
|
+
var POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13];
|
|
15
|
+
var SQRT_BASE = 1e7;
|
|
16
|
+
var MAX = 1e9;
|
|
17
|
+
function clone(configObject) {
|
|
18
|
+
var div, convertBase, parseNumeric, P = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = {
|
|
19
|
+
prefix: "",
|
|
20
|
+
groupSize: 3,
|
|
21
|
+
secondaryGroupSize: 0,
|
|
22
|
+
groupSeparator: ",",
|
|
23
|
+
decimalSeparator: ".",
|
|
24
|
+
fractionGroupSize: 0,
|
|
25
|
+
fractionGroupSeparator: "\xA0",
|
|
26
|
+
// non-breaking space
|
|
27
|
+
suffix: ""
|
|
28
|
+
}, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true;
|
|
29
|
+
function BigNumber2(v, b) {
|
|
30
|
+
var alphabet, c, caseChanged, e, i, isNum, len, str, x = this;
|
|
31
|
+
if (!(x instanceof BigNumber2)) return new BigNumber2(v, b);
|
|
32
|
+
if (b == null) {
|
|
33
|
+
if (v && v._isBigNumber === true) {
|
|
34
|
+
x.s = v.s;
|
|
35
|
+
if (!v.c || v.e > MAX_EXP) {
|
|
36
|
+
x.c = x.e = null;
|
|
37
|
+
} else if (v.e < MIN_EXP) {
|
|
38
|
+
x.c = [x.e = 0];
|
|
39
|
+
} else {
|
|
40
|
+
x.e = v.e;
|
|
41
|
+
x.c = v.c.slice();
|
|
42
|
+
}
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
if ((isNum = typeof v == "number") && v * 0 == 0) {
|
|
46
|
+
x.s = 1 / v < 0 ? (v = -v, -1) : 1;
|
|
47
|
+
if (v === ~~v) {
|
|
48
|
+
for (e = 0, i = v; i >= 10; i /= 10, e++) ;
|
|
49
|
+
if (e > MAX_EXP) {
|
|
50
|
+
x.c = x.e = null;
|
|
51
|
+
} else {
|
|
52
|
+
x.e = e;
|
|
53
|
+
x.c = [v];
|
|
54
|
+
}
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
str = String(v);
|
|
58
|
+
} else {
|
|
59
|
+
if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);
|
|
60
|
+
x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;
|
|
61
|
+
}
|
|
62
|
+
if ((e = str.indexOf(".")) > -1) str = str.replace(".", "");
|
|
63
|
+
if ((i = str.search(/e/i)) > 0) {
|
|
64
|
+
if (e < 0) e = i;
|
|
65
|
+
e += +str.slice(i + 1);
|
|
66
|
+
str = str.substring(0, i);
|
|
67
|
+
} else if (e < 0) {
|
|
68
|
+
e = str.length;
|
|
69
|
+
}
|
|
70
|
+
} else {
|
|
71
|
+
intCheck(b, 2, ALPHABET.length, "Base");
|
|
72
|
+
if (b == 10 && alphabetHasNormalDecimalDigits) {
|
|
73
|
+
x = new BigNumber2(v);
|
|
74
|
+
return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);
|
|
75
|
+
}
|
|
76
|
+
str = String(v);
|
|
77
|
+
if (isNum = typeof v == "number") {
|
|
78
|
+
if (v * 0 != 0) return parseNumeric(x, str, isNum, b);
|
|
79
|
+
x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;
|
|
80
|
+
if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) {
|
|
81
|
+
throw Error(tooManyDigits + v);
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;
|
|
85
|
+
}
|
|
86
|
+
alphabet = ALPHABET.slice(0, b);
|
|
87
|
+
e = i = 0;
|
|
88
|
+
for (len = str.length; i < len; i++) {
|
|
89
|
+
if (alphabet.indexOf(c = str.charAt(i)) < 0) {
|
|
90
|
+
if (c == ".") {
|
|
91
|
+
if (i > e) {
|
|
92
|
+
e = len;
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
} else if (!caseChanged) {
|
|
96
|
+
if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) {
|
|
97
|
+
caseChanged = true;
|
|
98
|
+
i = -1;
|
|
99
|
+
e = 0;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return parseNumeric(x, String(v), isNum, b);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
isNum = false;
|
|
107
|
+
str = convertBase(str, b, 10, x.s);
|
|
108
|
+
if ((e = str.indexOf(".")) > -1) str = str.replace(".", "");
|
|
109
|
+
else e = str.length;
|
|
110
|
+
}
|
|
111
|
+
for (i = 0; str.charCodeAt(i) === 48; i++) ;
|
|
112
|
+
for (len = str.length; str.charCodeAt(--len) === 48; ) ;
|
|
113
|
+
if (str = str.slice(i, ++len)) {
|
|
114
|
+
len -= i;
|
|
115
|
+
if (isNum && BigNumber2.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {
|
|
116
|
+
throw Error(tooManyDigits + x.s * v);
|
|
117
|
+
}
|
|
118
|
+
if ((e = e - i - 1) > MAX_EXP) {
|
|
119
|
+
x.c = x.e = null;
|
|
120
|
+
} else if (e < MIN_EXP) {
|
|
121
|
+
x.c = [x.e = 0];
|
|
122
|
+
} else {
|
|
123
|
+
x.e = e;
|
|
124
|
+
x.c = [];
|
|
125
|
+
i = (e + 1) % LOG_BASE;
|
|
126
|
+
if (e < 0) i += LOG_BASE;
|
|
127
|
+
if (i < len) {
|
|
128
|
+
if (i) x.c.push(+str.slice(0, i));
|
|
129
|
+
for (len -= LOG_BASE; i < len; ) {
|
|
130
|
+
x.c.push(+str.slice(i, i += LOG_BASE));
|
|
131
|
+
}
|
|
132
|
+
i = LOG_BASE - (str = str.slice(i)).length;
|
|
133
|
+
} else {
|
|
134
|
+
i -= len;
|
|
135
|
+
}
|
|
136
|
+
for (; i--; str += "0") ;
|
|
137
|
+
x.c.push(+str);
|
|
138
|
+
}
|
|
139
|
+
} else {
|
|
140
|
+
x.c = [x.e = 0];
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
BigNumber2.clone = clone;
|
|
144
|
+
BigNumber2.ROUND_UP = 0;
|
|
145
|
+
BigNumber2.ROUND_DOWN = 1;
|
|
146
|
+
BigNumber2.ROUND_CEIL = 2;
|
|
147
|
+
BigNumber2.ROUND_FLOOR = 3;
|
|
148
|
+
BigNumber2.ROUND_HALF_UP = 4;
|
|
149
|
+
BigNumber2.ROUND_HALF_DOWN = 5;
|
|
150
|
+
BigNumber2.ROUND_HALF_EVEN = 6;
|
|
151
|
+
BigNumber2.ROUND_HALF_CEIL = 7;
|
|
152
|
+
BigNumber2.ROUND_HALF_FLOOR = 8;
|
|
153
|
+
BigNumber2.EUCLID = 9;
|
|
154
|
+
BigNumber2.config = BigNumber2.set = function(obj) {
|
|
155
|
+
var p, v;
|
|
156
|
+
if (obj != null) {
|
|
157
|
+
if (typeof obj == "object") {
|
|
158
|
+
if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) {
|
|
159
|
+
v = obj[p];
|
|
160
|
+
intCheck(v, 0, MAX, p);
|
|
161
|
+
DECIMAL_PLACES = v;
|
|
162
|
+
}
|
|
163
|
+
if (obj.hasOwnProperty(p = "ROUNDING_MODE")) {
|
|
164
|
+
v = obj[p];
|
|
165
|
+
intCheck(v, 0, 8, p);
|
|
166
|
+
ROUNDING_MODE = v;
|
|
167
|
+
}
|
|
168
|
+
if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) {
|
|
169
|
+
v = obj[p];
|
|
170
|
+
if (v && v.pop) {
|
|
171
|
+
intCheck(v[0], -MAX, 0, p);
|
|
172
|
+
intCheck(v[1], 0, MAX, p);
|
|
173
|
+
TO_EXP_NEG = v[0];
|
|
174
|
+
TO_EXP_POS = v[1];
|
|
175
|
+
} else {
|
|
176
|
+
intCheck(v, -MAX, MAX, p);
|
|
177
|
+
TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
if (obj.hasOwnProperty(p = "RANGE")) {
|
|
181
|
+
v = obj[p];
|
|
182
|
+
if (v && v.pop) {
|
|
183
|
+
intCheck(v[0], -MAX, -1, p);
|
|
184
|
+
intCheck(v[1], 1, MAX, p);
|
|
185
|
+
MIN_EXP = v[0];
|
|
186
|
+
MAX_EXP = v[1];
|
|
187
|
+
} else {
|
|
188
|
+
intCheck(v, -MAX, MAX, p);
|
|
189
|
+
if (v) {
|
|
190
|
+
MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);
|
|
191
|
+
} else {
|
|
192
|
+
throw Error(bignumberError + p + " cannot be zero: " + v);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (obj.hasOwnProperty(p = "CRYPTO")) {
|
|
197
|
+
v = obj[p];
|
|
198
|
+
if (v === !!v) {
|
|
199
|
+
if (v) {
|
|
200
|
+
if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
|
|
201
|
+
CRYPTO = v;
|
|
202
|
+
} else {
|
|
203
|
+
CRYPTO = !v;
|
|
204
|
+
throw Error(bignumberError + "crypto unavailable");
|
|
205
|
+
}
|
|
206
|
+
} else {
|
|
207
|
+
CRYPTO = v;
|
|
208
|
+
}
|
|
209
|
+
} else {
|
|
210
|
+
throw Error(bignumberError + p + " not true or false: " + v);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (obj.hasOwnProperty(p = "MODULO_MODE")) {
|
|
214
|
+
v = obj[p];
|
|
215
|
+
intCheck(v, 0, 9, p);
|
|
216
|
+
MODULO_MODE = v;
|
|
217
|
+
}
|
|
218
|
+
if (obj.hasOwnProperty(p = "POW_PRECISION")) {
|
|
219
|
+
v = obj[p];
|
|
220
|
+
intCheck(v, 0, MAX, p);
|
|
221
|
+
POW_PRECISION = v;
|
|
222
|
+
}
|
|
223
|
+
if (obj.hasOwnProperty(p = "FORMAT")) {
|
|
224
|
+
v = obj[p];
|
|
225
|
+
if (typeof v == "object") FORMAT = v;
|
|
226
|
+
else throw Error(bignumberError + p + " not an object: " + v);
|
|
227
|
+
}
|
|
228
|
+
if (obj.hasOwnProperty(p = "ALPHABET")) {
|
|
229
|
+
v = obj[p];
|
|
230
|
+
if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) {
|
|
231
|
+
alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789";
|
|
232
|
+
ALPHABET = v;
|
|
233
|
+
} else {
|
|
234
|
+
throw Error(bignumberError + p + " invalid: " + v);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
} else {
|
|
238
|
+
throw Error(bignumberError + "Object expected: " + obj);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return {
|
|
242
|
+
DECIMAL_PLACES,
|
|
243
|
+
ROUNDING_MODE,
|
|
244
|
+
EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],
|
|
245
|
+
RANGE: [MIN_EXP, MAX_EXP],
|
|
246
|
+
CRYPTO,
|
|
247
|
+
MODULO_MODE,
|
|
248
|
+
POW_PRECISION,
|
|
249
|
+
FORMAT,
|
|
250
|
+
ALPHABET
|
|
251
|
+
};
|
|
252
|
+
};
|
|
253
|
+
BigNumber2.isBigNumber = function(v) {
|
|
254
|
+
if (!v || v._isBigNumber !== true) return false;
|
|
255
|
+
if (!BigNumber2.DEBUG) return true;
|
|
256
|
+
var i, n, c = v.c, e = v.e, s = v.s;
|
|
257
|
+
out: if ({}.toString.call(c) == "[object Array]") {
|
|
258
|
+
if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {
|
|
259
|
+
if (c[0] === 0) {
|
|
260
|
+
if (e === 0 && c.length === 1) return true;
|
|
261
|
+
break out;
|
|
262
|
+
}
|
|
263
|
+
i = (e + 1) % LOG_BASE;
|
|
264
|
+
if (i < 1) i += LOG_BASE;
|
|
265
|
+
if (String(c[0]).length == i) {
|
|
266
|
+
for (i = 0; i < c.length; i++) {
|
|
267
|
+
n = c[i];
|
|
268
|
+
if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;
|
|
269
|
+
}
|
|
270
|
+
if (n !== 0) return true;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
} else if (c === null && e === null && (s === null || s === 1 || s === -1)) {
|
|
274
|
+
return true;
|
|
275
|
+
}
|
|
276
|
+
throw Error(bignumberError + "Invalid BigNumber: " + v);
|
|
277
|
+
};
|
|
278
|
+
BigNumber2.maximum = BigNumber2.max = function() {
|
|
279
|
+
return maxOrMin(arguments, -1);
|
|
280
|
+
};
|
|
281
|
+
BigNumber2.minimum = BigNumber2.min = function() {
|
|
282
|
+
return maxOrMin(arguments, 1);
|
|
283
|
+
};
|
|
284
|
+
BigNumber2.random = (function() {
|
|
285
|
+
var pow2_53 = 9007199254740992;
|
|
286
|
+
var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() {
|
|
287
|
+
return mathfloor(Math.random() * pow2_53);
|
|
288
|
+
} : function() {
|
|
289
|
+
return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0);
|
|
290
|
+
};
|
|
291
|
+
return function(dp) {
|
|
292
|
+
var a, b, e, k, v, i = 0, c = [], rand = new BigNumber2(ONE);
|
|
293
|
+
if (dp == null) dp = DECIMAL_PLACES;
|
|
294
|
+
else intCheck(dp, 0, MAX);
|
|
295
|
+
k = mathceil(dp / LOG_BASE);
|
|
296
|
+
if (CRYPTO) {
|
|
297
|
+
if (crypto.getRandomValues) {
|
|
298
|
+
a = crypto.getRandomValues(new Uint32Array(k *= 2));
|
|
299
|
+
for (; i < k; ) {
|
|
300
|
+
v = a[i] * 131072 + (a[i + 1] >>> 11);
|
|
301
|
+
if (v >= 9e15) {
|
|
302
|
+
b = crypto.getRandomValues(new Uint32Array(2));
|
|
303
|
+
a[i] = b[0];
|
|
304
|
+
a[i + 1] = b[1];
|
|
305
|
+
} else {
|
|
306
|
+
c.push(v % 1e14);
|
|
307
|
+
i += 2;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
i = k / 2;
|
|
311
|
+
} else if (crypto.randomBytes) {
|
|
312
|
+
a = crypto.randomBytes(k *= 7);
|
|
313
|
+
for (; i < k; ) {
|
|
314
|
+
v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];
|
|
315
|
+
if (v >= 9e15) {
|
|
316
|
+
crypto.randomBytes(7).copy(a, i);
|
|
317
|
+
} else {
|
|
318
|
+
c.push(v % 1e14);
|
|
319
|
+
i += 7;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
i = k / 7;
|
|
323
|
+
} else {
|
|
324
|
+
CRYPTO = false;
|
|
325
|
+
throw Error(bignumberError + "crypto unavailable");
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (!CRYPTO) {
|
|
329
|
+
for (; i < k; ) {
|
|
330
|
+
v = random53bitInt();
|
|
331
|
+
if (v < 9e15) c[i++] = v % 1e14;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
k = c[--i];
|
|
335
|
+
dp %= LOG_BASE;
|
|
336
|
+
if (k && dp) {
|
|
337
|
+
v = POWS_TEN[LOG_BASE - dp];
|
|
338
|
+
c[i] = mathfloor(k / v) * v;
|
|
339
|
+
}
|
|
340
|
+
for (; c[i] === 0; c.pop(), i--) ;
|
|
341
|
+
if (i < 0) {
|
|
342
|
+
c = [e = 0];
|
|
343
|
+
} else {
|
|
344
|
+
for (e = -1; c[0] === 0; c.splice(0, 1), e -= LOG_BASE) ;
|
|
345
|
+
for (i = 1, v = c[0]; v >= 10; v /= 10, i++) ;
|
|
346
|
+
if (i < LOG_BASE) e -= LOG_BASE - i;
|
|
347
|
+
}
|
|
348
|
+
rand.e = e;
|
|
349
|
+
rand.c = c;
|
|
350
|
+
return rand;
|
|
351
|
+
};
|
|
352
|
+
})();
|
|
353
|
+
BigNumber2.sum = function() {
|
|
354
|
+
var i = 1, args = arguments, sum = new BigNumber2(args[0]);
|
|
355
|
+
for (; i < args.length; ) sum = sum.plus(args[i++]);
|
|
356
|
+
return sum;
|
|
357
|
+
};
|
|
358
|
+
convertBase = /* @__PURE__ */ (function() {
|
|
359
|
+
var decimal = "0123456789";
|
|
360
|
+
function toBaseOut(str, baseIn, baseOut, alphabet) {
|
|
361
|
+
var j, arr = [0], arrL, i = 0, len = str.length;
|
|
362
|
+
for (; i < len; ) {
|
|
363
|
+
for (arrL = arr.length; arrL--; arr[arrL] *= baseIn) ;
|
|
364
|
+
arr[0] += alphabet.indexOf(str.charAt(i++));
|
|
365
|
+
for (j = 0; j < arr.length; j++) {
|
|
366
|
+
if (arr[j] > baseOut - 1) {
|
|
367
|
+
if (arr[j + 1] == null) arr[j + 1] = 0;
|
|
368
|
+
arr[j + 1] += arr[j] / baseOut | 0;
|
|
369
|
+
arr[j] %= baseOut;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return arr.reverse();
|
|
374
|
+
}
|
|
375
|
+
return function(str, baseIn, baseOut, sign, callerIsToString) {
|
|
376
|
+
var alphabet, d, e, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE;
|
|
377
|
+
if (i >= 0) {
|
|
378
|
+
k = POW_PRECISION;
|
|
379
|
+
POW_PRECISION = 0;
|
|
380
|
+
str = str.replace(".", "");
|
|
381
|
+
y = new BigNumber2(baseIn);
|
|
382
|
+
x = y.pow(str.length - i);
|
|
383
|
+
POW_PRECISION = k;
|
|
384
|
+
y.c = toBaseOut(
|
|
385
|
+
toFixedPoint(coeffToString(x.c), x.e, "0"),
|
|
386
|
+
10,
|
|
387
|
+
baseOut,
|
|
388
|
+
decimal
|
|
389
|
+
);
|
|
390
|
+
y.e = y.c.length;
|
|
391
|
+
}
|
|
392
|
+
xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET));
|
|
393
|
+
e = k = xc.length;
|
|
394
|
+
for (; xc[--k] == 0; xc.pop()) ;
|
|
395
|
+
if (!xc[0]) return alphabet.charAt(0);
|
|
396
|
+
if (i < 0) {
|
|
397
|
+
--e;
|
|
398
|
+
} else {
|
|
399
|
+
x.c = xc;
|
|
400
|
+
x.e = e;
|
|
401
|
+
x.s = sign;
|
|
402
|
+
x = div(x, y, dp, rm, baseOut);
|
|
403
|
+
xc = x.c;
|
|
404
|
+
r = x.r;
|
|
405
|
+
e = x.e;
|
|
406
|
+
}
|
|
407
|
+
d = e + dp + 1;
|
|
408
|
+
i = xc[d];
|
|
409
|
+
k = baseOut / 2;
|
|
410
|
+
r = r || d < 0 || xc[d + 1] != null;
|
|
411
|
+
r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7));
|
|
412
|
+
if (d < 1 || !xc[0]) {
|
|
413
|
+
str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);
|
|
414
|
+
} else {
|
|
415
|
+
xc.length = d;
|
|
416
|
+
if (r) {
|
|
417
|
+
for (--baseOut; ++xc[--d] > baseOut; ) {
|
|
418
|
+
xc[d] = 0;
|
|
419
|
+
if (!d) {
|
|
420
|
+
++e;
|
|
421
|
+
xc = [1].concat(xc);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
for (k = xc.length; !xc[--k]; ) ;
|
|
426
|
+
for (i = 0, str = ""; i <= k; str += alphabet.charAt(xc[i++])) ;
|
|
427
|
+
str = toFixedPoint(str, e, alphabet.charAt(0));
|
|
428
|
+
}
|
|
429
|
+
return str;
|
|
430
|
+
};
|
|
431
|
+
})();
|
|
432
|
+
div = /* @__PURE__ */ (function() {
|
|
433
|
+
function multiply(x, k, base) {
|
|
434
|
+
var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0;
|
|
435
|
+
for (x = x.slice(); i--; ) {
|
|
436
|
+
xlo = x[i] % SQRT_BASE;
|
|
437
|
+
xhi = x[i] / SQRT_BASE | 0;
|
|
438
|
+
m = khi * xlo + xhi * klo;
|
|
439
|
+
temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry;
|
|
440
|
+
carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;
|
|
441
|
+
x[i] = temp % base;
|
|
442
|
+
}
|
|
443
|
+
if (carry) x = [carry].concat(x);
|
|
444
|
+
return x;
|
|
445
|
+
}
|
|
446
|
+
function compare2(a, b, aL, bL) {
|
|
447
|
+
var i, cmp;
|
|
448
|
+
if (aL != bL) {
|
|
449
|
+
cmp = aL > bL ? 1 : -1;
|
|
450
|
+
} else {
|
|
451
|
+
for (i = cmp = 0; i < aL; i++) {
|
|
452
|
+
if (a[i] != b[i]) {
|
|
453
|
+
cmp = a[i] > b[i] ? 1 : -1;
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return cmp;
|
|
459
|
+
}
|
|
460
|
+
function subtract(a, b, aL, base) {
|
|
461
|
+
var i = 0;
|
|
462
|
+
for (; aL--; ) {
|
|
463
|
+
a[aL] -= i;
|
|
464
|
+
i = a[aL] < b[aL] ? 1 : 0;
|
|
465
|
+
a[aL] = i * base + a[aL] - b[aL];
|
|
466
|
+
}
|
|
467
|
+
for (; !a[0] && a.length > 1; a.splice(0, 1)) ;
|
|
468
|
+
}
|
|
469
|
+
return function(x, y, dp, rm, base) {
|
|
470
|
+
var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c;
|
|
471
|
+
if (!xc || !xc[0] || !yc || !yc[0]) {
|
|
472
|
+
return new BigNumber2(
|
|
473
|
+
// Return NaN if either NaN, or both Infinity or 0.
|
|
474
|
+
!x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : (
|
|
475
|
+
// Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
|
|
476
|
+
xc && xc[0] == 0 || !yc ? s * 0 : s / 0
|
|
477
|
+
)
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
q = new BigNumber2(s);
|
|
481
|
+
qc = q.c = [];
|
|
482
|
+
e = x.e - y.e;
|
|
483
|
+
s = dp + e + 1;
|
|
484
|
+
if (!base) {
|
|
485
|
+
base = BASE;
|
|
486
|
+
e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);
|
|
487
|
+
s = s / LOG_BASE | 0;
|
|
488
|
+
}
|
|
489
|
+
for (i = 0; yc[i] == (xc[i] || 0); i++) ;
|
|
490
|
+
if (yc[i] > (xc[i] || 0)) e--;
|
|
491
|
+
if (s < 0) {
|
|
492
|
+
qc.push(1);
|
|
493
|
+
more = true;
|
|
494
|
+
} else {
|
|
495
|
+
xL = xc.length;
|
|
496
|
+
yL = yc.length;
|
|
497
|
+
i = 0;
|
|
498
|
+
s += 2;
|
|
499
|
+
n = mathfloor(base / (yc[0] + 1));
|
|
500
|
+
if (n > 1) {
|
|
501
|
+
yc = multiply(yc, n, base);
|
|
502
|
+
xc = multiply(xc, n, base);
|
|
503
|
+
yL = yc.length;
|
|
504
|
+
xL = xc.length;
|
|
505
|
+
}
|
|
506
|
+
xi = yL;
|
|
507
|
+
rem = xc.slice(0, yL);
|
|
508
|
+
remL = rem.length;
|
|
509
|
+
for (; remL < yL; rem[remL++] = 0) ;
|
|
510
|
+
yz = yc.slice();
|
|
511
|
+
yz = [0].concat(yz);
|
|
512
|
+
yc0 = yc[0];
|
|
513
|
+
if (yc[1] >= base / 2) yc0++;
|
|
514
|
+
do {
|
|
515
|
+
n = 0;
|
|
516
|
+
cmp = compare2(yc, rem, yL, remL);
|
|
517
|
+
if (cmp < 0) {
|
|
518
|
+
rem0 = rem[0];
|
|
519
|
+
if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
|
|
520
|
+
n = mathfloor(rem0 / yc0);
|
|
521
|
+
if (n > 1) {
|
|
522
|
+
if (n >= base) n = base - 1;
|
|
523
|
+
prod = multiply(yc, n, base);
|
|
524
|
+
prodL = prod.length;
|
|
525
|
+
remL = rem.length;
|
|
526
|
+
while (compare2(prod, rem, prodL, remL) == 1) {
|
|
527
|
+
n--;
|
|
528
|
+
subtract(prod, yL < prodL ? yz : yc, prodL, base);
|
|
529
|
+
prodL = prod.length;
|
|
530
|
+
cmp = 1;
|
|
531
|
+
}
|
|
532
|
+
} else {
|
|
533
|
+
if (n == 0) {
|
|
534
|
+
cmp = n = 1;
|
|
535
|
+
}
|
|
536
|
+
prod = yc.slice();
|
|
537
|
+
prodL = prod.length;
|
|
538
|
+
}
|
|
539
|
+
if (prodL < remL) prod = [0].concat(prod);
|
|
540
|
+
subtract(rem, prod, remL, base);
|
|
541
|
+
remL = rem.length;
|
|
542
|
+
if (cmp == -1) {
|
|
543
|
+
while (compare2(yc, rem, yL, remL) < 1) {
|
|
544
|
+
n++;
|
|
545
|
+
subtract(rem, yL < remL ? yz : yc, remL, base);
|
|
546
|
+
remL = rem.length;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
} else if (cmp === 0) {
|
|
550
|
+
n++;
|
|
551
|
+
rem = [0];
|
|
552
|
+
}
|
|
553
|
+
qc[i++] = n;
|
|
554
|
+
if (rem[0]) {
|
|
555
|
+
rem[remL++] = xc[xi] || 0;
|
|
556
|
+
} else {
|
|
557
|
+
rem = [xc[xi]];
|
|
558
|
+
remL = 1;
|
|
559
|
+
}
|
|
560
|
+
} while ((xi++ < xL || rem[0] != null) && s--);
|
|
561
|
+
more = rem[0] != null;
|
|
562
|
+
if (!qc[0]) qc.splice(0, 1);
|
|
563
|
+
}
|
|
564
|
+
if (base == BASE) {
|
|
565
|
+
for (i = 1, s = qc[0]; s >= 10; s /= 10, i++) ;
|
|
566
|
+
round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);
|
|
567
|
+
} else {
|
|
568
|
+
q.e = e;
|
|
569
|
+
q.r = +more;
|
|
570
|
+
}
|
|
571
|
+
return q;
|
|
572
|
+
};
|
|
573
|
+
})();
|
|
574
|
+
function format(n, i, rm, id) {
|
|
575
|
+
var c0, e, ne, len, str;
|
|
576
|
+
if (rm == null) rm = ROUNDING_MODE;
|
|
577
|
+
else intCheck(rm, 0, 8);
|
|
578
|
+
if (!n.c) return n.toString();
|
|
579
|
+
c0 = n.c[0];
|
|
580
|
+
ne = n.e;
|
|
581
|
+
if (i == null) {
|
|
582
|
+
str = coeffToString(n.c);
|
|
583
|
+
str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS) ? toExponential(str, ne) : toFixedPoint(str, ne, "0");
|
|
584
|
+
} else {
|
|
585
|
+
n = round(new BigNumber2(n), i, rm);
|
|
586
|
+
e = n.e;
|
|
587
|
+
str = coeffToString(n.c);
|
|
588
|
+
len = str.length;
|
|
589
|
+
if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {
|
|
590
|
+
for (; len < i; str += "0", len++) ;
|
|
591
|
+
str = toExponential(str, e);
|
|
592
|
+
} else {
|
|
593
|
+
i -= ne;
|
|
594
|
+
str = toFixedPoint(str, e, "0");
|
|
595
|
+
if (e + 1 > len) {
|
|
596
|
+
if (--i > 0) for (str += "."; i--; str += "0") ;
|
|
597
|
+
} else {
|
|
598
|
+
i += e - len;
|
|
599
|
+
if (i > 0) {
|
|
600
|
+
if (e + 1 == len) str += ".";
|
|
601
|
+
for (; i--; str += "0") ;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return n.s < 0 && c0 ? "-" + str : str;
|
|
607
|
+
}
|
|
608
|
+
function maxOrMin(args, n) {
|
|
609
|
+
var k, y, i = 1, x = new BigNumber2(args[0]);
|
|
610
|
+
for (; i < args.length; i++) {
|
|
611
|
+
y = new BigNumber2(args[i]);
|
|
612
|
+
if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {
|
|
613
|
+
x = y;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
return x;
|
|
617
|
+
}
|
|
618
|
+
function normalise(n, c, e) {
|
|
619
|
+
var i = 1, j = c.length;
|
|
620
|
+
for (; !c[--j]; c.pop()) ;
|
|
621
|
+
for (j = c[0]; j >= 10; j /= 10, i++) ;
|
|
622
|
+
if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {
|
|
623
|
+
n.c = n.e = null;
|
|
624
|
+
} else if (e < MIN_EXP) {
|
|
625
|
+
n.c = [n.e = 0];
|
|
626
|
+
} else {
|
|
627
|
+
n.e = e;
|
|
628
|
+
n.c = c;
|
|
629
|
+
}
|
|
630
|
+
return n;
|
|
631
|
+
}
|
|
632
|
+
parseNumeric = /* @__PURE__ */ (function() {
|
|
633
|
+
var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
|
|
634
|
+
return function(x, str, isNum, b) {
|
|
635
|
+
var base, s = isNum ? str : str.replace(whitespaceOrPlus, "");
|
|
636
|
+
if (isInfinityOrNaN.test(s)) {
|
|
637
|
+
x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
|
|
638
|
+
} else {
|
|
639
|
+
if (!isNum) {
|
|
640
|
+
s = s.replace(basePrefix, function(m, p1, p2) {
|
|
641
|
+
base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8;
|
|
642
|
+
return !b || b == base ? p1 : m;
|
|
643
|
+
});
|
|
644
|
+
if (b) {
|
|
645
|
+
base = b;
|
|
646
|
+
s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1");
|
|
647
|
+
}
|
|
648
|
+
if (str != s) return new BigNumber2(s, base);
|
|
649
|
+
}
|
|
650
|
+
if (BigNumber2.DEBUG) {
|
|
651
|
+
throw Error(bignumberError + "Not a" + (b ? " base " + b : "") + " number: " + str);
|
|
652
|
+
}
|
|
653
|
+
x.s = null;
|
|
654
|
+
}
|
|
655
|
+
x.c = x.e = null;
|
|
656
|
+
};
|
|
657
|
+
})();
|
|
658
|
+
function round(x, sd, rm, r) {
|
|
659
|
+
var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN;
|
|
660
|
+
if (xc) {
|
|
661
|
+
out: {
|
|
662
|
+
for (d = 1, k = xc[0]; k >= 10; k /= 10, d++) ;
|
|
663
|
+
i = sd - d;
|
|
664
|
+
if (i < 0) {
|
|
665
|
+
i += LOG_BASE;
|
|
666
|
+
j = sd;
|
|
667
|
+
n = xc[ni = 0];
|
|
668
|
+
rd = mathfloor(n / pows10[d - j - 1] % 10);
|
|
669
|
+
} else {
|
|
670
|
+
ni = mathceil((i + 1) / LOG_BASE);
|
|
671
|
+
if (ni >= xc.length) {
|
|
672
|
+
if (r) {
|
|
673
|
+
for (; xc.length <= ni; xc.push(0)) ;
|
|
674
|
+
n = rd = 0;
|
|
675
|
+
d = 1;
|
|
676
|
+
i %= LOG_BASE;
|
|
677
|
+
j = i - LOG_BASE + 1;
|
|
678
|
+
} else {
|
|
679
|
+
break out;
|
|
680
|
+
}
|
|
681
|
+
} else {
|
|
682
|
+
n = k = xc[ni];
|
|
683
|
+
for (d = 1; k >= 10; k /= 10, d++) ;
|
|
684
|
+
i %= LOG_BASE;
|
|
685
|
+
j = i - LOG_BASE + d;
|
|
686
|
+
rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
r = r || sd < 0 || // Are there any non-zero digits after the rounding digit?
|
|
690
|
+
// The expression n % pows10[d - j - 1] returns all digits of n to the right
|
|
691
|
+
// of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
|
|
692
|
+
xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);
|
|
693
|
+
r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && // Check whether the digit to the left of the rounding digit is odd.
|
|
694
|
+
(i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7));
|
|
695
|
+
if (sd < 1 || !xc[0]) {
|
|
696
|
+
xc.length = 0;
|
|
697
|
+
if (r) {
|
|
698
|
+
sd -= x.e + 1;
|
|
699
|
+
xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];
|
|
700
|
+
x.e = -sd || 0;
|
|
701
|
+
} else {
|
|
702
|
+
xc[0] = x.e = 0;
|
|
703
|
+
}
|
|
704
|
+
return x;
|
|
705
|
+
}
|
|
706
|
+
if (i == 0) {
|
|
707
|
+
xc.length = ni;
|
|
708
|
+
k = 1;
|
|
709
|
+
ni--;
|
|
710
|
+
} else {
|
|
711
|
+
xc.length = ni + 1;
|
|
712
|
+
k = pows10[LOG_BASE - i];
|
|
713
|
+
xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;
|
|
714
|
+
}
|
|
715
|
+
if (r) {
|
|
716
|
+
for (; ; ) {
|
|
717
|
+
if (ni == 0) {
|
|
718
|
+
for (i = 1, j = xc[0]; j >= 10; j /= 10, i++) ;
|
|
719
|
+
j = xc[0] += k;
|
|
720
|
+
for (k = 1; j >= 10; j /= 10, k++) ;
|
|
721
|
+
if (i != k) {
|
|
722
|
+
x.e++;
|
|
723
|
+
if (xc[0] == BASE) xc[0] = 1;
|
|
724
|
+
}
|
|
725
|
+
break;
|
|
726
|
+
} else {
|
|
727
|
+
xc[ni] += k;
|
|
728
|
+
if (xc[ni] != BASE) break;
|
|
729
|
+
xc[ni--] = 0;
|
|
730
|
+
k = 1;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
for (i = xc.length; xc[--i] === 0; xc.pop()) ;
|
|
735
|
+
}
|
|
736
|
+
if (x.e > MAX_EXP) {
|
|
737
|
+
x.c = x.e = null;
|
|
738
|
+
} else if (x.e < MIN_EXP) {
|
|
739
|
+
x.c = [x.e = 0];
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
return x;
|
|
743
|
+
}
|
|
744
|
+
function valueOf(n) {
|
|
745
|
+
var str, e = n.e;
|
|
746
|
+
if (e === null) return n.toString();
|
|
747
|
+
str = coeffToString(n.c);
|
|
748
|
+
str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(str, e) : toFixedPoint(str, e, "0");
|
|
749
|
+
return n.s < 0 ? "-" + str : str;
|
|
750
|
+
}
|
|
751
|
+
P.absoluteValue = P.abs = function() {
|
|
752
|
+
var x = new BigNumber2(this);
|
|
753
|
+
if (x.s < 0) x.s = 1;
|
|
754
|
+
return x;
|
|
755
|
+
};
|
|
756
|
+
P.comparedTo = function(y, b) {
|
|
757
|
+
return compare(this, new BigNumber2(y, b));
|
|
758
|
+
};
|
|
759
|
+
P.decimalPlaces = P.dp = function(dp, rm) {
|
|
760
|
+
var c, n, v, x = this;
|
|
761
|
+
if (dp != null) {
|
|
762
|
+
intCheck(dp, 0, MAX);
|
|
763
|
+
if (rm == null) rm = ROUNDING_MODE;
|
|
764
|
+
else intCheck(rm, 0, 8);
|
|
765
|
+
return round(new BigNumber2(x), dp + x.e + 1, rm);
|
|
766
|
+
}
|
|
767
|
+
if (!(c = x.c)) return null;
|
|
768
|
+
n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;
|
|
769
|
+
if (v = c[v]) for (; v % 10 == 0; v /= 10, n--) ;
|
|
770
|
+
if (n < 0) n = 0;
|
|
771
|
+
return n;
|
|
772
|
+
};
|
|
773
|
+
P.dividedBy = P.div = function(y, b) {
|
|
774
|
+
return div(this, new BigNumber2(y, b), DECIMAL_PLACES, ROUNDING_MODE);
|
|
775
|
+
};
|
|
776
|
+
P.dividedToIntegerBy = P.idiv = function(y, b) {
|
|
777
|
+
return div(this, new BigNumber2(y, b), 0, 1);
|
|
778
|
+
};
|
|
779
|
+
P.exponentiatedBy = P.pow = function(n, m) {
|
|
780
|
+
var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this;
|
|
781
|
+
n = new BigNumber2(n);
|
|
782
|
+
if (n.c && !n.isInteger()) {
|
|
783
|
+
throw Error(bignumberError + "Exponent not an integer: " + valueOf(n));
|
|
784
|
+
}
|
|
785
|
+
if (m != null) m = new BigNumber2(m);
|
|
786
|
+
nIsBig = n.e > 14;
|
|
787
|
+
if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {
|
|
788
|
+
y = new BigNumber2(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));
|
|
789
|
+
return m ? y.mod(m) : y;
|
|
790
|
+
}
|
|
791
|
+
nIsNeg = n.s < 0;
|
|
792
|
+
if (m) {
|
|
793
|
+
if (m.c ? !m.c[0] : !m.s) return new BigNumber2(NaN);
|
|
794
|
+
isModExp = !nIsNeg && x.isInteger() && m.isInteger();
|
|
795
|
+
if (isModExp) x = x.mod(m);
|
|
796
|
+
} else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {
|
|
797
|
+
k = x.s < 0 && isOdd(n) ? -0 : 0;
|
|
798
|
+
if (x.e > -1) k = 1 / k;
|
|
799
|
+
return new BigNumber2(nIsNeg ? 1 / k : k);
|
|
800
|
+
} else if (POW_PRECISION) {
|
|
801
|
+
k = mathceil(POW_PRECISION / LOG_BASE + 2);
|
|
802
|
+
}
|
|
803
|
+
if (nIsBig) {
|
|
804
|
+
half = new BigNumber2(0.5);
|
|
805
|
+
if (nIsNeg) n.s = 1;
|
|
806
|
+
nIsOdd = isOdd(n);
|
|
807
|
+
} else {
|
|
808
|
+
i = Math.abs(+valueOf(n));
|
|
809
|
+
nIsOdd = i % 2;
|
|
810
|
+
}
|
|
811
|
+
y = new BigNumber2(ONE);
|
|
812
|
+
for (; ; ) {
|
|
813
|
+
if (nIsOdd) {
|
|
814
|
+
y = y.times(x);
|
|
815
|
+
if (!y.c) break;
|
|
816
|
+
if (k) {
|
|
817
|
+
if (y.c.length > k) y.c.length = k;
|
|
818
|
+
} else if (isModExp) {
|
|
819
|
+
y = y.mod(m);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
if (i) {
|
|
823
|
+
i = mathfloor(i / 2);
|
|
824
|
+
if (i === 0) break;
|
|
825
|
+
nIsOdd = i % 2;
|
|
826
|
+
} else {
|
|
827
|
+
n = n.times(half);
|
|
828
|
+
round(n, n.e + 1, 1);
|
|
829
|
+
if (n.e > 14) {
|
|
830
|
+
nIsOdd = isOdd(n);
|
|
831
|
+
} else {
|
|
832
|
+
i = +valueOf(n);
|
|
833
|
+
if (i === 0) break;
|
|
834
|
+
nIsOdd = i % 2;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
x = x.times(x);
|
|
838
|
+
if (k) {
|
|
839
|
+
if (x.c && x.c.length > k) x.c.length = k;
|
|
840
|
+
} else if (isModExp) {
|
|
841
|
+
x = x.mod(m);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
if (isModExp) return y;
|
|
845
|
+
if (nIsNeg) y = ONE.div(y);
|
|
846
|
+
return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;
|
|
847
|
+
};
|
|
848
|
+
P.integerValue = function(rm) {
|
|
849
|
+
var n = new BigNumber2(this);
|
|
850
|
+
if (rm == null) rm = ROUNDING_MODE;
|
|
851
|
+
else intCheck(rm, 0, 8);
|
|
852
|
+
return round(n, n.e + 1, rm);
|
|
853
|
+
};
|
|
854
|
+
P.isEqualTo = P.eq = function(y, b) {
|
|
855
|
+
return compare(this, new BigNumber2(y, b)) === 0;
|
|
856
|
+
};
|
|
857
|
+
P.isFinite = function() {
|
|
858
|
+
return !!this.c;
|
|
859
|
+
};
|
|
860
|
+
P.isGreaterThan = P.gt = function(y, b) {
|
|
861
|
+
return compare(this, new BigNumber2(y, b)) > 0;
|
|
862
|
+
};
|
|
863
|
+
P.isGreaterThanOrEqualTo = P.gte = function(y, b) {
|
|
864
|
+
return (b = compare(this, new BigNumber2(y, b))) === 1 || b === 0;
|
|
865
|
+
};
|
|
866
|
+
P.isInteger = function() {
|
|
867
|
+
return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;
|
|
868
|
+
};
|
|
869
|
+
P.isLessThan = P.lt = function(y, b) {
|
|
870
|
+
return compare(this, new BigNumber2(y, b)) < 0;
|
|
871
|
+
};
|
|
872
|
+
P.isLessThanOrEqualTo = P.lte = function(y, b) {
|
|
873
|
+
return (b = compare(this, new BigNumber2(y, b))) === -1 || b === 0;
|
|
874
|
+
};
|
|
875
|
+
P.isNaN = function() {
|
|
876
|
+
return !this.s;
|
|
877
|
+
};
|
|
878
|
+
P.isNegative = function() {
|
|
879
|
+
return this.s < 0;
|
|
880
|
+
};
|
|
881
|
+
P.isPositive = function() {
|
|
882
|
+
return this.s > 0;
|
|
883
|
+
};
|
|
884
|
+
P.isZero = function() {
|
|
885
|
+
return !!this.c && this.c[0] == 0;
|
|
886
|
+
};
|
|
887
|
+
P.minus = function(y, b) {
|
|
888
|
+
var i, j, t, xLTy, x = this, a = x.s;
|
|
889
|
+
y = new BigNumber2(y, b);
|
|
890
|
+
b = y.s;
|
|
891
|
+
if (!a || !b) return new BigNumber2(NaN);
|
|
892
|
+
if (a != b) {
|
|
893
|
+
y.s = -b;
|
|
894
|
+
return x.plus(y);
|
|
895
|
+
}
|
|
896
|
+
var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
|
|
897
|
+
if (!xe || !ye) {
|
|
898
|
+
if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber2(yc ? x : NaN);
|
|
899
|
+
if (!xc[0] || !yc[0]) {
|
|
900
|
+
return yc[0] ? (y.s = -b, y) : new BigNumber2(xc[0] ? x : (
|
|
901
|
+
// IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
|
|
902
|
+
ROUNDING_MODE == 3 ? -0 : 0
|
|
903
|
+
));
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
xe = bitFloor(xe);
|
|
907
|
+
ye = bitFloor(ye);
|
|
908
|
+
xc = xc.slice();
|
|
909
|
+
if (a = xe - ye) {
|
|
910
|
+
if (xLTy = a < 0) {
|
|
911
|
+
a = -a;
|
|
912
|
+
t = xc;
|
|
913
|
+
} else {
|
|
914
|
+
ye = xe;
|
|
915
|
+
t = yc;
|
|
916
|
+
}
|
|
917
|
+
t.reverse();
|
|
918
|
+
for (b = a; b--; t.push(0)) ;
|
|
919
|
+
t.reverse();
|
|
920
|
+
} else {
|
|
921
|
+
j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;
|
|
922
|
+
for (a = b = 0; b < j; b++) {
|
|
923
|
+
if (xc[b] != yc[b]) {
|
|
924
|
+
xLTy = xc[b] < yc[b];
|
|
925
|
+
break;
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
if (xLTy) {
|
|
930
|
+
t = xc;
|
|
931
|
+
xc = yc;
|
|
932
|
+
yc = t;
|
|
933
|
+
y.s = -y.s;
|
|
934
|
+
}
|
|
935
|
+
b = (j = yc.length) - (i = xc.length);
|
|
936
|
+
if (b > 0) for (; b--; xc[i++] = 0) ;
|
|
937
|
+
b = BASE - 1;
|
|
938
|
+
for (; j > a; ) {
|
|
939
|
+
if (xc[--j] < yc[j]) {
|
|
940
|
+
for (i = j; i && !xc[--i]; xc[i] = b) ;
|
|
941
|
+
--xc[i];
|
|
942
|
+
xc[j] += BASE;
|
|
943
|
+
}
|
|
944
|
+
xc[j] -= yc[j];
|
|
945
|
+
}
|
|
946
|
+
for (; xc[0] == 0; xc.splice(0, 1), --ye) ;
|
|
947
|
+
if (!xc[0]) {
|
|
948
|
+
y.s = ROUNDING_MODE == 3 ? -1 : 1;
|
|
949
|
+
y.c = [y.e = 0];
|
|
950
|
+
return y;
|
|
951
|
+
}
|
|
952
|
+
return normalise(y, xc, ye);
|
|
953
|
+
};
|
|
954
|
+
P.modulo = P.mod = function(y, b) {
|
|
955
|
+
var q, s, x = this;
|
|
956
|
+
y = new BigNumber2(y, b);
|
|
957
|
+
if (!x.c || !y.s || y.c && !y.c[0]) {
|
|
958
|
+
return new BigNumber2(NaN);
|
|
959
|
+
} else if (!y.c || x.c && !x.c[0]) {
|
|
960
|
+
return new BigNumber2(x);
|
|
961
|
+
}
|
|
962
|
+
if (MODULO_MODE == 9) {
|
|
963
|
+
s = y.s;
|
|
964
|
+
y.s = 1;
|
|
965
|
+
q = div(x, y, 0, 3);
|
|
966
|
+
y.s = s;
|
|
967
|
+
q.s *= s;
|
|
968
|
+
} else {
|
|
969
|
+
q = div(x, y, 0, MODULO_MODE);
|
|
970
|
+
}
|
|
971
|
+
y = x.minus(q.times(y));
|
|
972
|
+
if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;
|
|
973
|
+
return y;
|
|
974
|
+
};
|
|
975
|
+
P.multipliedBy = P.times = function(y, b) {
|
|
976
|
+
var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber2(y, b)).c;
|
|
977
|
+
if (!xc || !yc || !xc[0] || !yc[0]) {
|
|
978
|
+
if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {
|
|
979
|
+
y.c = y.e = y.s = null;
|
|
980
|
+
} else {
|
|
981
|
+
y.s *= x.s;
|
|
982
|
+
if (!xc || !yc) {
|
|
983
|
+
y.c = y.e = null;
|
|
984
|
+
} else {
|
|
985
|
+
y.c = [0];
|
|
986
|
+
y.e = 0;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
return y;
|
|
990
|
+
}
|
|
991
|
+
e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);
|
|
992
|
+
y.s *= x.s;
|
|
993
|
+
xcL = xc.length;
|
|
994
|
+
ycL = yc.length;
|
|
995
|
+
if (xcL < ycL) {
|
|
996
|
+
zc = xc;
|
|
997
|
+
xc = yc;
|
|
998
|
+
yc = zc;
|
|
999
|
+
i = xcL;
|
|
1000
|
+
xcL = ycL;
|
|
1001
|
+
ycL = i;
|
|
1002
|
+
}
|
|
1003
|
+
for (i = xcL + ycL, zc = []; i--; zc.push(0)) ;
|
|
1004
|
+
base = BASE;
|
|
1005
|
+
sqrtBase = SQRT_BASE;
|
|
1006
|
+
for (i = ycL; --i >= 0; ) {
|
|
1007
|
+
c = 0;
|
|
1008
|
+
ylo = yc[i] % sqrtBase;
|
|
1009
|
+
yhi = yc[i] / sqrtBase | 0;
|
|
1010
|
+
for (k = xcL, j = i + k; j > i; ) {
|
|
1011
|
+
xlo = xc[--k] % sqrtBase;
|
|
1012
|
+
xhi = xc[k] / sqrtBase | 0;
|
|
1013
|
+
m = yhi * xlo + xhi * ylo;
|
|
1014
|
+
xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c;
|
|
1015
|
+
c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;
|
|
1016
|
+
zc[j--] = xlo % base;
|
|
1017
|
+
}
|
|
1018
|
+
zc[j] = c;
|
|
1019
|
+
}
|
|
1020
|
+
if (c) {
|
|
1021
|
+
++e;
|
|
1022
|
+
} else {
|
|
1023
|
+
zc.splice(0, 1);
|
|
1024
|
+
}
|
|
1025
|
+
return normalise(y, zc, e);
|
|
1026
|
+
};
|
|
1027
|
+
P.negated = function() {
|
|
1028
|
+
var x = new BigNumber2(this);
|
|
1029
|
+
x.s = -x.s || null;
|
|
1030
|
+
return x;
|
|
1031
|
+
};
|
|
1032
|
+
P.plus = function(y, b) {
|
|
1033
|
+
var t, x = this, a = x.s;
|
|
1034
|
+
y = new BigNumber2(y, b);
|
|
1035
|
+
b = y.s;
|
|
1036
|
+
if (!a || !b) return new BigNumber2(NaN);
|
|
1037
|
+
if (a != b) {
|
|
1038
|
+
y.s = -b;
|
|
1039
|
+
return x.minus(y);
|
|
1040
|
+
}
|
|
1041
|
+
var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c;
|
|
1042
|
+
if (!xe || !ye) {
|
|
1043
|
+
if (!xc || !yc) return new BigNumber2(a / 0);
|
|
1044
|
+
if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber2(xc[0] ? x : a * 0);
|
|
1045
|
+
}
|
|
1046
|
+
xe = bitFloor(xe);
|
|
1047
|
+
ye = bitFloor(ye);
|
|
1048
|
+
xc = xc.slice();
|
|
1049
|
+
if (a = xe - ye) {
|
|
1050
|
+
if (a > 0) {
|
|
1051
|
+
ye = xe;
|
|
1052
|
+
t = yc;
|
|
1053
|
+
} else {
|
|
1054
|
+
a = -a;
|
|
1055
|
+
t = xc;
|
|
1056
|
+
}
|
|
1057
|
+
t.reverse();
|
|
1058
|
+
for (; a--; t.push(0)) ;
|
|
1059
|
+
t.reverse();
|
|
1060
|
+
}
|
|
1061
|
+
a = xc.length;
|
|
1062
|
+
b = yc.length;
|
|
1063
|
+
if (a - b < 0) {
|
|
1064
|
+
t = yc;
|
|
1065
|
+
yc = xc;
|
|
1066
|
+
xc = t;
|
|
1067
|
+
b = a;
|
|
1068
|
+
}
|
|
1069
|
+
for (a = 0; b; ) {
|
|
1070
|
+
a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;
|
|
1071
|
+
xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
|
|
1072
|
+
}
|
|
1073
|
+
if (a) {
|
|
1074
|
+
xc = [a].concat(xc);
|
|
1075
|
+
++ye;
|
|
1076
|
+
}
|
|
1077
|
+
return normalise(y, xc, ye);
|
|
1078
|
+
};
|
|
1079
|
+
P.precision = P.sd = function(sd, rm) {
|
|
1080
|
+
var c, n, v, x = this;
|
|
1081
|
+
if (sd != null && sd !== !!sd) {
|
|
1082
|
+
intCheck(sd, 1, MAX);
|
|
1083
|
+
if (rm == null) rm = ROUNDING_MODE;
|
|
1084
|
+
else intCheck(rm, 0, 8);
|
|
1085
|
+
return round(new BigNumber2(x), sd, rm);
|
|
1086
|
+
}
|
|
1087
|
+
if (!(c = x.c)) return null;
|
|
1088
|
+
v = c.length - 1;
|
|
1089
|
+
n = v * LOG_BASE + 1;
|
|
1090
|
+
if (v = c[v]) {
|
|
1091
|
+
for (; v % 10 == 0; v /= 10, n--) ;
|
|
1092
|
+
for (v = c[0]; v >= 10; v /= 10, n++) ;
|
|
1093
|
+
}
|
|
1094
|
+
if (sd && x.e + 1 > n) n = x.e + 1;
|
|
1095
|
+
return n;
|
|
1096
|
+
};
|
|
1097
|
+
P.shiftedBy = function(k) {
|
|
1098
|
+
intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);
|
|
1099
|
+
return this.times("1e" + k);
|
|
1100
|
+
};
|
|
1101
|
+
P.squareRoot = P.sqrt = function() {
|
|
1102
|
+
var m, n, r, rep, t, x = this, c = x.c, s = x.s, e = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5");
|
|
1103
|
+
if (s !== 1 || !c || !c[0]) {
|
|
1104
|
+
return new BigNumber2(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);
|
|
1105
|
+
}
|
|
1106
|
+
s = Math.sqrt(+valueOf(x));
|
|
1107
|
+
if (s == 0 || s == 1 / 0) {
|
|
1108
|
+
n = coeffToString(c);
|
|
1109
|
+
if ((n.length + e) % 2 == 0) n += "0";
|
|
1110
|
+
s = Math.sqrt(+n);
|
|
1111
|
+
e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);
|
|
1112
|
+
if (s == 1 / 0) {
|
|
1113
|
+
n = "5e" + e;
|
|
1114
|
+
} else {
|
|
1115
|
+
n = s.toExponential();
|
|
1116
|
+
n = n.slice(0, n.indexOf("e") + 1) + e;
|
|
1117
|
+
}
|
|
1118
|
+
r = new BigNumber2(n);
|
|
1119
|
+
} else {
|
|
1120
|
+
r = new BigNumber2(s + "");
|
|
1121
|
+
}
|
|
1122
|
+
if (r.c[0]) {
|
|
1123
|
+
e = r.e;
|
|
1124
|
+
s = e + dp;
|
|
1125
|
+
if (s < 3) s = 0;
|
|
1126
|
+
for (; ; ) {
|
|
1127
|
+
t = r;
|
|
1128
|
+
r = half.times(t.plus(div(x, t, dp, 1)));
|
|
1129
|
+
if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {
|
|
1130
|
+
if (r.e < e) --s;
|
|
1131
|
+
n = n.slice(s - 3, s + 1);
|
|
1132
|
+
if (n == "9999" || !rep && n == "4999") {
|
|
1133
|
+
if (!rep) {
|
|
1134
|
+
round(t, t.e + DECIMAL_PLACES + 2, 0);
|
|
1135
|
+
if (t.times(t).eq(x)) {
|
|
1136
|
+
r = t;
|
|
1137
|
+
break;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
dp += 4;
|
|
1141
|
+
s += 4;
|
|
1142
|
+
rep = 1;
|
|
1143
|
+
} else {
|
|
1144
|
+
if (!+n || !+n.slice(1) && n.charAt(0) == "5") {
|
|
1145
|
+
round(r, r.e + DECIMAL_PLACES + 2, 1);
|
|
1146
|
+
m = !r.times(r).eq(x);
|
|
1147
|
+
}
|
|
1148
|
+
break;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);
|
|
1154
|
+
};
|
|
1155
|
+
P.toExponential = function(dp, rm) {
|
|
1156
|
+
if (dp != null) {
|
|
1157
|
+
intCheck(dp, 0, MAX);
|
|
1158
|
+
dp++;
|
|
1159
|
+
}
|
|
1160
|
+
return format(this, dp, rm, 1);
|
|
1161
|
+
};
|
|
1162
|
+
P.toFixed = function(dp, rm) {
|
|
1163
|
+
if (dp != null) {
|
|
1164
|
+
intCheck(dp, 0, MAX);
|
|
1165
|
+
dp = dp + this.e + 1;
|
|
1166
|
+
}
|
|
1167
|
+
return format(this, dp, rm);
|
|
1168
|
+
};
|
|
1169
|
+
P.toFormat = function(dp, rm, format2) {
|
|
1170
|
+
var str, x = this;
|
|
1171
|
+
if (format2 == null) {
|
|
1172
|
+
if (dp != null && rm && typeof rm == "object") {
|
|
1173
|
+
format2 = rm;
|
|
1174
|
+
rm = null;
|
|
1175
|
+
} else if (dp && typeof dp == "object") {
|
|
1176
|
+
format2 = dp;
|
|
1177
|
+
dp = rm = null;
|
|
1178
|
+
} else {
|
|
1179
|
+
format2 = FORMAT;
|
|
1180
|
+
}
|
|
1181
|
+
} else if (typeof format2 != "object") {
|
|
1182
|
+
throw Error(bignumberError + "Argument not an object: " + format2);
|
|
1183
|
+
}
|
|
1184
|
+
str = x.toFixed(dp, rm);
|
|
1185
|
+
if (x.c) {
|
|
1186
|
+
var i, arr = str.split("."), g1 = +format2.groupSize, g2 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length;
|
|
1187
|
+
if (g2) {
|
|
1188
|
+
i = g1;
|
|
1189
|
+
g1 = g2;
|
|
1190
|
+
g2 = i;
|
|
1191
|
+
len -= i;
|
|
1192
|
+
}
|
|
1193
|
+
if (g1 > 0 && len > 0) {
|
|
1194
|
+
i = len % g1 || g1;
|
|
1195
|
+
intPart = intDigits.substr(0, i);
|
|
1196
|
+
for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);
|
|
1197
|
+
if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);
|
|
1198
|
+
if (isNeg) intPart = "-" + intPart;
|
|
1199
|
+
}
|
|
1200
|
+
str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g2 = +format2.fractionGroupSize) ? fractionPart.replace(
|
|
1201
|
+
new RegExp("\\d{" + g2 + "}\\B", "g"),
|
|
1202
|
+
"$&" + (format2.fractionGroupSeparator || "")
|
|
1203
|
+
) : fractionPart) : intPart;
|
|
1204
|
+
}
|
|
1205
|
+
return (format2.prefix || "") + str + (format2.suffix || "");
|
|
1206
|
+
};
|
|
1207
|
+
P.toFraction = function(md) {
|
|
1208
|
+
var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, x = this, xc = x.c;
|
|
1209
|
+
if (md != null) {
|
|
1210
|
+
n = new BigNumber2(md);
|
|
1211
|
+
if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {
|
|
1212
|
+
throw Error(bignumberError + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n));
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
if (!xc) return new BigNumber2(x);
|
|
1216
|
+
d = new BigNumber2(ONE);
|
|
1217
|
+
n1 = d0 = new BigNumber2(ONE);
|
|
1218
|
+
d1 = n0 = new BigNumber2(ONE);
|
|
1219
|
+
s = coeffToString(xc);
|
|
1220
|
+
e = d.e = s.length - x.e - 1;
|
|
1221
|
+
d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];
|
|
1222
|
+
md = !md || n.comparedTo(d) > 0 ? e > 0 ? d : n1 : n;
|
|
1223
|
+
exp = MAX_EXP;
|
|
1224
|
+
MAX_EXP = 1 / 0;
|
|
1225
|
+
n = new BigNumber2(s);
|
|
1226
|
+
n0.c[0] = 0;
|
|
1227
|
+
for (; ; ) {
|
|
1228
|
+
q = div(n, d, 0, 1);
|
|
1229
|
+
d2 = d0.plus(q.times(d1));
|
|
1230
|
+
if (d2.comparedTo(md) == 1) break;
|
|
1231
|
+
d0 = d1;
|
|
1232
|
+
d1 = d2;
|
|
1233
|
+
n1 = n0.plus(q.times(d2 = n1));
|
|
1234
|
+
n0 = d2;
|
|
1235
|
+
d = n.minus(q.times(d2 = d));
|
|
1236
|
+
n = d2;
|
|
1237
|
+
}
|
|
1238
|
+
d2 = div(md.minus(d0), d1, 0, 1);
|
|
1239
|
+
n0 = n0.plus(d2.times(n1));
|
|
1240
|
+
d0 = d0.plus(d2.times(d1));
|
|
1241
|
+
n0.s = n1.s = x.s;
|
|
1242
|
+
e = e * 2;
|
|
1243
|
+
r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(
|
|
1244
|
+
div(n0, d0, e, ROUNDING_MODE).minus(x).abs()
|
|
1245
|
+
) < 1 ? [n1, d1] : [n0, d0];
|
|
1246
|
+
MAX_EXP = exp;
|
|
1247
|
+
return r;
|
|
1248
|
+
};
|
|
1249
|
+
P.toNumber = function() {
|
|
1250
|
+
return +valueOf(this);
|
|
1251
|
+
};
|
|
1252
|
+
P.toPrecision = function(sd, rm) {
|
|
1253
|
+
if (sd != null) intCheck(sd, 1, MAX);
|
|
1254
|
+
return format(this, sd, rm, 2);
|
|
1255
|
+
};
|
|
1256
|
+
P.toString = function(b) {
|
|
1257
|
+
var str, n = this, s = n.s, e = n.e;
|
|
1258
|
+
if (e === null) {
|
|
1259
|
+
if (s) {
|
|
1260
|
+
str = "Infinity";
|
|
1261
|
+
if (s < 0) str = "-" + str;
|
|
1262
|
+
} else {
|
|
1263
|
+
str = "NaN";
|
|
1264
|
+
}
|
|
1265
|
+
} else {
|
|
1266
|
+
if (b == null) {
|
|
1267
|
+
str = e <= TO_EXP_NEG || e >= TO_EXP_POS ? toExponential(coeffToString(n.c), e) : toFixedPoint(coeffToString(n.c), e, "0");
|
|
1268
|
+
} else if (b === 10 && alphabetHasNormalDecimalDigits) {
|
|
1269
|
+
n = round(new BigNumber2(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);
|
|
1270
|
+
str = toFixedPoint(coeffToString(n.c), n.e, "0");
|
|
1271
|
+
} else {
|
|
1272
|
+
intCheck(b, 2, ALPHABET.length, "Base");
|
|
1273
|
+
str = convertBase(toFixedPoint(coeffToString(n.c), e, "0"), 10, b, s, true);
|
|
1274
|
+
}
|
|
1275
|
+
if (s < 0 && n.c[0]) str = "-" + str;
|
|
1276
|
+
}
|
|
1277
|
+
return str;
|
|
1278
|
+
};
|
|
1279
|
+
P.valueOf = P.toJSON = function() {
|
|
1280
|
+
return valueOf(this);
|
|
1281
|
+
};
|
|
1282
|
+
P._isBigNumber = true;
|
|
1283
|
+
P[Symbol.toStringTag] = "BigNumber";
|
|
1284
|
+
P[Symbol.for("nodejs.util.inspect.custom")] = P.valueOf;
|
|
1285
|
+
if (configObject != null) BigNumber2.set(configObject);
|
|
1286
|
+
return BigNumber2;
|
|
1287
|
+
}
|
|
1288
|
+
function bitFloor(n) {
|
|
1289
|
+
var i = n | 0;
|
|
1290
|
+
return n > 0 || n === i ? i : i - 1;
|
|
1291
|
+
}
|
|
1292
|
+
function coeffToString(a) {
|
|
1293
|
+
var s, z, i = 1, j = a.length, r = a[0] + "";
|
|
1294
|
+
for (; i < j; ) {
|
|
1295
|
+
s = a[i++] + "";
|
|
1296
|
+
z = LOG_BASE - s.length;
|
|
1297
|
+
for (; z--; s = "0" + s) ;
|
|
1298
|
+
r += s;
|
|
1299
|
+
}
|
|
1300
|
+
for (j = r.length; r.charCodeAt(--j) === 48; ) ;
|
|
1301
|
+
return r.slice(0, j + 1 || 1);
|
|
1302
|
+
}
|
|
1303
|
+
function compare(x, y) {
|
|
1304
|
+
var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e;
|
|
1305
|
+
if (!i || !j) return null;
|
|
1306
|
+
a = xc && !xc[0];
|
|
1307
|
+
b = yc && !yc[0];
|
|
1308
|
+
if (a || b) return a ? b ? 0 : -j : i;
|
|
1309
|
+
if (i != j) return i;
|
|
1310
|
+
a = i < 0;
|
|
1311
|
+
b = k == l;
|
|
1312
|
+
if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;
|
|
1313
|
+
if (!b) return k > l ^ a ? 1 : -1;
|
|
1314
|
+
j = (k = xc.length) < (l = yc.length) ? k : l;
|
|
1315
|
+
for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;
|
|
1316
|
+
return k == l ? 0 : k > l ^ a ? 1 : -1;
|
|
1317
|
+
}
|
|
1318
|
+
function intCheck(n, min, max, name) {
|
|
1319
|
+
if (n < min || n > max || n !== mathfloor(n)) {
|
|
1320
|
+
throw Error(bignumberError + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n));
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
function isOdd(n) {
|
|
1324
|
+
var k = n.c.length - 1;
|
|
1325
|
+
return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;
|
|
1326
|
+
}
|
|
1327
|
+
function toExponential(str, e) {
|
|
1328
|
+
return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e < 0 ? "e" : "e+") + e;
|
|
1329
|
+
}
|
|
1330
|
+
function toFixedPoint(str, e, z) {
|
|
1331
|
+
var len, zs;
|
|
1332
|
+
if (e < 0) {
|
|
1333
|
+
for (zs = z + "."; ++e; zs += z) ;
|
|
1334
|
+
str = zs + str;
|
|
1335
|
+
} else {
|
|
1336
|
+
len = str.length;
|
|
1337
|
+
if (++e > len) {
|
|
1338
|
+
for (zs = z, e -= len; --e; zs += z) ;
|
|
1339
|
+
str += zs;
|
|
1340
|
+
} else if (e < len) {
|
|
1341
|
+
str = str.slice(0, e) + "." + str.slice(e);
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
return str;
|
|
1345
|
+
}
|
|
1346
|
+
var BigNumber = clone();
|
|
1347
|
+
var bignumber_default = BigNumber;
|
|
1348
|
+
|
|
1349
|
+
// src/protocol.ts
|
|
1350
|
+
var RLUSD_ASSET = "524C555344000000000000000000000000000000";
|
|
1351
|
+
var PAYMENT_HEADERS = {
|
|
1352
|
+
required: "PAYMENT-REQUIRED",
|
|
1353
|
+
signature: "PAYMENT-SIGNATURE",
|
|
1354
|
+
response: "PAYMENT-RESPONSE"
|
|
1355
|
+
};
|
|
1356
|
+
function isRecord(value) {
|
|
1357
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1358
|
+
}
|
|
1359
|
+
function positiveAmount(value, integer = false) {
|
|
1360
|
+
if (typeof value !== "string" || value.length > 100 || !(integer ? /^\d+$/ : /^\d+(?:\.\d+)?(?:[eE][+-]?\d{1,2})?$/).test(value)) {
|
|
1361
|
+
throw new Error("Amount must be a positive decimal string.");
|
|
1362
|
+
}
|
|
1363
|
+
const amount = new bignumber_default(value);
|
|
1364
|
+
if (!amount.isFinite() || amount.lte(0) || amount.gt("100000000000") || (integer ? !amount.isInteger() : amount.precision() > 16)) {
|
|
1365
|
+
throw new Error("Amount is outside the supported XRPL range.");
|
|
1366
|
+
}
|
|
1367
|
+
return amount;
|
|
1368
|
+
}
|
|
1369
|
+
function amountEquals(a, b) {
|
|
1370
|
+
return positiveAmount(a).eq(positiveAmount(b));
|
|
1371
|
+
}
|
|
1372
|
+
function xrpToDrops(amount) {
|
|
1373
|
+
const drops = positiveAmount(amount).times(1e6);
|
|
1374
|
+
if (!drops.isInteger()) throw new Error("XRP amounts must be whole drops.");
|
|
1375
|
+
return drops.toFixed(0);
|
|
1376
|
+
}
|
|
1377
|
+
function validateRequirements(value) {
|
|
1378
|
+
if (!isRecord(value) || value.scheme !== "exact" || !["xrpl:0", "xrpl:1"].includes(value.network) || !["XRP", RLUSD_ASSET].includes(value.asset) || typeof value.payTo !== "string" || !Number.isInteger(value.maxTimeoutSeconds) || value.maxTimeoutSeconds < 10 || value.maxTimeoutSeconds > 600 || !isRecord(value.extra) || value.extra.areFeesSponsored !== false || value.extra.assetTransferMethod !== void 0 && value.extra.assetTransferMethod !== "sequence" || value.extra.invoiceId !== void 0 && (typeof value.extra.invoiceId !== "string" || value.extra.invoiceId.length < 1 || value.extra.invoiceId.length > 1024) || value.asset !== "XRP" && typeof value.extra.issuer !== "string" || value.asset === "XRP" && value.extra.issuer !== void 0 || value.extra.destinationTag !== void 0 && (!Number.isInteger(value.extra.destinationTag) || value.extra.destinationTag < 0 || value.extra.destinationTag > 4294967295)) {
|
|
1379
|
+
throw new Error("Unsupported or invalid XRPL payment requirements.");
|
|
1380
|
+
}
|
|
1381
|
+
positiveAmount(value.amount, value.asset === "XRP");
|
|
1382
|
+
}
|
|
1383
|
+
function requirementsKey(value) {
|
|
1384
|
+
validateRequirements(value);
|
|
1385
|
+
return JSON.stringify([
|
|
1386
|
+
value.scheme,
|
|
1387
|
+
value.network,
|
|
1388
|
+
value.asset,
|
|
1389
|
+
value.amount,
|
|
1390
|
+
value.payTo,
|
|
1391
|
+
value.maxTimeoutSeconds,
|
|
1392
|
+
value.extra.areFeesSponsored,
|
|
1393
|
+
value.extra.assetTransferMethod ?? "sequence",
|
|
1394
|
+
value.extra.invoiceId ?? null,
|
|
1395
|
+
value.extra.issuer ?? null,
|
|
1396
|
+
value.extra.destinationTag ?? null
|
|
1397
|
+
]);
|
|
1398
|
+
}
|
|
1399
|
+
function validatePayload(value, requirement) {
|
|
1400
|
+
validateRequirements(requirement);
|
|
1401
|
+
if (!isRecord(value) || value.x402Version !== 2 || !isRecord(value.payload) || typeof value.payload.signedTxBlob !== "string" || !/^[A-Fa-f0-9]+$/.test(value.payload.signedTxBlob) || value.payload.signedTxBlob.length % 2 !== 0 || value.payload.signedTxBlob.length > 16384 || requirementsKey(value.accepted) !== requirementsKey(requirement)) {
|
|
1402
|
+
throw new Error("Payment payload does not match the required terms.");
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
function encodePaymentHeader(value) {
|
|
1406
|
+
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
|
1407
|
+
let binary = "";
|
|
1408
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1409
|
+
return btoa(binary);
|
|
1410
|
+
}
|
|
1411
|
+
function decodePaymentHeader(value) {
|
|
1412
|
+
if (value.length > 32768 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) throw new Error("Invalid payment header.");
|
|
1413
|
+
const bytes = Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
|
|
1414
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
// src/server.ts
|
|
1418
|
+
function invoiceHash(invoiceId) {
|
|
1419
|
+
return crypto2.createHash("sha256").update(invoiceId).digest("hex").toUpperCase();
|
|
1420
|
+
}
|
|
1421
|
+
function matchesInvoice(invoice, requirement) {
|
|
1422
|
+
const invoiceId = requirement.extra.invoiceId;
|
|
1423
|
+
return invoiceId === void 0 || typeof invoice === "string" && invoice.toUpperCase() === invoiceHash(invoiceId);
|
|
1424
|
+
}
|
|
1425
|
+
function assertAddress(value) {
|
|
1426
|
+
if (typeof value !== "string" || !isValidClassicAddress(value)) throw new Error("A valid XRPL classic address is required.");
|
|
1427
|
+
}
|
|
1428
|
+
function decodedPayment(payload, requirement, maxFeeDrops) {
|
|
1429
|
+
validatePayload(payload, requirement);
|
|
1430
|
+
assertAddress(requirement.payTo);
|
|
1431
|
+
if (requirement.extra.issuer) assertAddress(requirement.extra.issuer);
|
|
1432
|
+
const tx = decode(payload.payload.signedTxBlob);
|
|
1433
|
+
validate(tx);
|
|
1434
|
+
if (!verifySignature(payload.payload.signedTxBlob) || tx.Signers !== void 0) throw new Error("Invalid or unsupported transaction signature.");
|
|
1435
|
+
assertAddress(tx.Account);
|
|
1436
|
+
if (tx.TransactionType !== "Payment" || tx.Destination !== requirement.payTo || tx.DestinationTag !== requirement.extra.destinationTag || tx.NetworkID !== void 0 || tx.Delegate !== void 0 || tx.Memos !== void 0 || tx.Paths !== void 0 || tx.DeliverMin !== void 0 || !Number.isInteger(tx.Flags ?? 0) || ((tx.Flags ?? 0) & 131072) !== 0 || tx.TicketSequence !== void 0 || !Number.isInteger(tx.Sequence) || tx.Sequence < 1 || !Number.isInteger(tx.LastLedgerSequence) || tx.LastLedgerSequence < 1 || !matchesInvoice(tx.InvoiceID, requirement) || tx.Amount !== void 0 && tx.DeliverMax !== void 0) {
|
|
1437
|
+
throw new Error("Signed transaction violates the XRPL exact payment terms.");
|
|
1438
|
+
}
|
|
1439
|
+
if (positiveAmount(tx.Fee, true).gt(positiveAmount(maxFeeDrops, true))) throw new Error("Transaction fee exceeds facilitator policy.");
|
|
1440
|
+
assertDeliveredAmount(tx.DeliverMax ?? tx.Amount, requirement);
|
|
1441
|
+
if (requirement.asset === "XRP") {
|
|
1442
|
+
if (tx.SendMax !== void 0) throw new Error("XRP payments must not include SendMax.");
|
|
1443
|
+
} else {
|
|
1444
|
+
if (!isRecord(tx.SendMax) || tx.SendMax.currency !== requirement.asset || tx.SendMax.issuer !== requirement.extra.issuer || positiveAmount(tx.SendMax.value).lt(positiveAmount(requirement.amount))) {
|
|
1445
|
+
throw new Error("Issued-currency payments require a matching SendMax.");
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
return tx;
|
|
1449
|
+
}
|
|
1450
|
+
function assertDeliveredAmount(amount, requirement) {
|
|
1451
|
+
if (requirement.asset === "XRP") {
|
|
1452
|
+
if (typeof amount !== "string" || !/^\d+$/.test(amount) || !amountEquals(amount, requirement.amount)) {
|
|
1453
|
+
throw new Error("Delivered XRP amount does not equal the required drops.");
|
|
1454
|
+
}
|
|
1455
|
+
} else if (!isRecord(amount) || amount.currency !== requirement.asset || amount.issuer !== requirement.extra.issuer || !amountEquals(amount.value, requirement.amount)) {
|
|
1456
|
+
throw new Error("Delivered token amount or issuer does not match the requirement.");
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
var XrplFacilitator = class {
|
|
1460
|
+
options;
|
|
1461
|
+
pending = /* @__PURE__ */ new Map();
|
|
1462
|
+
constructor(options = {}) {
|
|
1463
|
+
if (!options.reserveSettlement && process.env.NODE_ENV === "production") {
|
|
1464
|
+
throw new Error("Production facilitators require a shared atomic settlement store.");
|
|
1465
|
+
}
|
|
1466
|
+
positiveAmount(options.maxFeeDrops ?? "1000", true);
|
|
1467
|
+
this.options = options;
|
|
1468
|
+
}
|
|
1469
|
+
supported() {
|
|
1470
|
+
return {
|
|
1471
|
+
kinds: (this.options.networks ?? ["xrpl:0", "xrpl:1"]).map((network) => ({
|
|
1472
|
+
x402Version: 2,
|
|
1473
|
+
scheme: "exact",
|
|
1474
|
+
network,
|
|
1475
|
+
extra: { areFeesSponsored: false, assetTransferMethod: "sequence" }
|
|
1476
|
+
})),
|
|
1477
|
+
extensions: [],
|
|
1478
|
+
signers: {}
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
newClient(network) {
|
|
1482
|
+
if (!(this.options.networks ?? ["xrpl:0", "xrpl:1"]).includes(network)) throw new Error("Unsupported XRPL network.");
|
|
1483
|
+
if (this.options.createClient) return this.options.createClient(network);
|
|
1484
|
+
return new Client(this.options.endpoints?.[network] ?? (network === "xrpl:1" ? "wss://s.altnet.rippletest.net:51233" : "wss://s1.ripple.com"), { connectionTimeout: 5e3, timeout: 1e4 });
|
|
1485
|
+
}
|
|
1486
|
+
async verifyWithClient(payload, requirement, client) {
|
|
1487
|
+
const tx = decodedPayment(payload, requirement, this.options.maxFeeDrops ?? "1000");
|
|
1488
|
+
const [ledgerIndex, accountResponse] = await Promise.all([
|
|
1489
|
+
client.getLedgerIndex(),
|
|
1490
|
+
client.request({ command: "account_info", account: tx.Account, ledger_index: "validated" })
|
|
1491
|
+
]);
|
|
1492
|
+
const account = accountResponse.result.account_data;
|
|
1493
|
+
const signingAddress = deriveAddress(tx.SigningPubKey);
|
|
1494
|
+
const masterAuthorized = signingAddress === tx.Account && (account.Flags & 1048576) === 0;
|
|
1495
|
+
if (!masterAuthorized && signingAddress !== account.RegularKey || account.Sequence !== tx.Sequence) {
|
|
1496
|
+
throw new Error("Signer is unauthorized or account sequence is no longer current.");
|
|
1497
|
+
}
|
|
1498
|
+
if (tx.LastLedgerSequence <= ledgerIndex || tx.LastLedgerSequence > ledgerIndex + Math.ceil(requirement.maxTimeoutSeconds / 5) + 2) {
|
|
1499
|
+
throw new Error("Transaction ledger expiry is outside the allowed window.");
|
|
1500
|
+
}
|
|
1501
|
+
const unsigned = { ...tx };
|
|
1502
|
+
delete unsigned.TxnSignature;
|
|
1503
|
+
delete unsigned.SigningPubKey;
|
|
1504
|
+
const simulation = await client.request({ command: "simulate", tx_json: unsigned });
|
|
1505
|
+
if (simulation.result.engine_result !== "tesSUCCESS") throw new Error("Payment simulation did not succeed.");
|
|
1506
|
+
if (simulation.result.meta?.delivered_amount !== void 0) {
|
|
1507
|
+
assertDeliveredAmount(simulation.result.meta.delivered_amount, requirement);
|
|
1508
|
+
}
|
|
1509
|
+
return { tx, txHash: hashes.hashSignedTx(payload.payload.signedTxBlob) };
|
|
1510
|
+
}
|
|
1511
|
+
async verify(payload, requirement) {
|
|
1512
|
+
let client;
|
|
1513
|
+
try {
|
|
1514
|
+
decodedPayment(payload, requirement, this.options.maxFeeDrops ?? "1000");
|
|
1515
|
+
client = this.newClient(requirement.network);
|
|
1516
|
+
await client.connect();
|
|
1517
|
+
const { tx } = await this.verifyWithClient(payload, requirement, client);
|
|
1518
|
+
return { isValid: true, payer: tx.Account };
|
|
1519
|
+
} catch (error) {
|
|
1520
|
+
return { isValid: false, invalidReason: error instanceof Error ? error.message : "Verification failed." };
|
|
1521
|
+
} finally {
|
|
1522
|
+
await client?.disconnect().catch(() => void 0);
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
async reserve(txHash, seconds) {
|
|
1526
|
+
if (this.options.reserveSettlement) return this.options.reserveSettlement(txHash, seconds);
|
|
1527
|
+
const now = Date.now();
|
|
1528
|
+
for (const [hash, expiry] of this.pending) if (expiry <= now) this.pending.delete(hash);
|
|
1529
|
+
if (this.pending.has(txHash)) return false;
|
|
1530
|
+
if (this.pending.size >= 1e4) throw new Error("Settlement store capacity exceeded.");
|
|
1531
|
+
this.pending.set(txHash, now + seconds * 1e3);
|
|
1532
|
+
return true;
|
|
1533
|
+
}
|
|
1534
|
+
/** Recover a previously persisted, purchase-owned attempt. Never creates a new
|
|
1535
|
+
* authorization: a retry can only submit the identical signed transaction hash.
|
|
1536
|
+
* Do not use this as a replay-permitting replacement for settle(). */
|
|
1537
|
+
async recoverSettlement(payload, requirement, resubmit = false) {
|
|
1538
|
+
let client;
|
|
1539
|
+
let txHash = "";
|
|
1540
|
+
try {
|
|
1541
|
+
const signed = decodedPayment(payload, requirement, this.options.maxFeeDrops ?? "1000");
|
|
1542
|
+
txHash = hashes.hashSignedTx(payload.payload.signedTxBlob);
|
|
1543
|
+
client = this.newClient(requirement.network);
|
|
1544
|
+
await client.connect();
|
|
1545
|
+
let result;
|
|
1546
|
+
try {
|
|
1547
|
+
result = (await client.request({ command: "tx", transaction: txHash, binary: false })).result;
|
|
1548
|
+
} catch (error) {
|
|
1549
|
+
if (!resubmit || error?.data?.error !== "txnNotFound") throw error;
|
|
1550
|
+
await this.verifyWithClient(payload, requirement, client);
|
|
1551
|
+
await this.reserve(txHash, requirement.maxTimeoutSeconds + 120);
|
|
1552
|
+
result = (await client.submitAndWait(payload.payload.signedTxBlob)).result;
|
|
1553
|
+
}
|
|
1554
|
+
const tx = result.tx_json ?? result;
|
|
1555
|
+
if (result.validated !== true || !isRecord(result.meta) || result.meta.TransactionResult !== "tesSUCCESS" || (result.hash ?? tx.hash)?.toUpperCase() !== txHash || tx.TransactionType !== "Payment" || tx.Account !== signed.Account || tx.Destination !== requirement.payTo || tx.DestinationTag !== requirement.extra.destinationTag || !matchesInvoice(tx.InvoiceID, requirement)) {
|
|
1556
|
+
throw new Error("Recovery has not confirmed the recorded payment.");
|
|
1557
|
+
}
|
|
1558
|
+
assertDeliveredAmount(result.meta.delivered_amount, requirement);
|
|
1559
|
+
return { success: true, transaction: txHash, network: requirement.network, payer: signed.Account, amount: requirement.amount };
|
|
1560
|
+
} catch {
|
|
1561
|
+
return { success: false, errorReason: "payment_not_confirmed", transaction: txHash, network: requirement.network };
|
|
1562
|
+
} finally {
|
|
1563
|
+
await client?.disconnect().catch(() => void 0);
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
async settle(payload, requirement) {
|
|
1567
|
+
let client;
|
|
1568
|
+
let txHash = "";
|
|
1569
|
+
try {
|
|
1570
|
+
decodedPayment(payload, requirement, this.options.maxFeeDrops ?? "1000");
|
|
1571
|
+
client = this.newClient(requirement.network);
|
|
1572
|
+
await client.connect();
|
|
1573
|
+
const verified = await this.verifyWithClient(payload, requirement, client);
|
|
1574
|
+
txHash = verified.txHash;
|
|
1575
|
+
if (!await this.reserve(txHash, requirement.maxTimeoutSeconds + 120)) {
|
|
1576
|
+
return { success: false, errorReason: "duplicate_settlement", transaction: txHash, network: requirement.network };
|
|
1577
|
+
}
|
|
1578
|
+
const submitted = await client.submitAndWait(payload.payload.signedTxBlob);
|
|
1579
|
+
const result = submitted.result;
|
|
1580
|
+
const tx = result.tx_json ?? result;
|
|
1581
|
+
if (result.validated !== true || !isRecord(result.meta) || result.meta.TransactionResult !== "tesSUCCESS" || (result.hash ?? tx.hash)?.toUpperCase() !== txHash || tx.TransactionType !== "Payment" || tx.Account !== verified.tx.Account || tx.Destination !== requirement.payTo || tx.DestinationTag !== requirement.extra.destinationTag || !matchesInvoice(tx.InvoiceID, requirement)) {
|
|
1582
|
+
throw new Error("Settlement was not a successful validated payment matching the signed transaction.");
|
|
1583
|
+
}
|
|
1584
|
+
assertDeliveredAmount(result.meta.delivered_amount, requirement);
|
|
1585
|
+
return { success: true, transaction: txHash, network: requirement.network, payer: tx.Account, amount: requirement.amount };
|
|
1586
|
+
} catch (error) {
|
|
1587
|
+
return {
|
|
1588
|
+
success: false,
|
|
1589
|
+
errorReason: error instanceof Error ? error.message : "Settlement failed.",
|
|
1590
|
+
transaction: txHash,
|
|
1591
|
+
network: requirement?.network ?? ""
|
|
1592
|
+
};
|
|
1593
|
+
} finally {
|
|
1594
|
+
await client?.disconnect().catch(() => void 0);
|
|
1595
|
+
}
|
|
1596
|
+
}
|
|
1597
|
+
};
|
|
1598
|
+
function createPaymentRequirements(options, invoiceId) {
|
|
1599
|
+
assertAddress(options.payTo);
|
|
1600
|
+
if (options.currency !== "XRP" && options.currency !== "RLUSD") throw new Error("Unsupported currency.");
|
|
1601
|
+
if (options.currency === "RLUSD") assertAddress(options.issuer);
|
|
1602
|
+
const extra = {
|
|
1603
|
+
areFeesSponsored: false,
|
|
1604
|
+
assetTransferMethod: "sequence",
|
|
1605
|
+
invoiceId,
|
|
1606
|
+
...options.currency === "RLUSD" ? { issuer: options.issuer } : {},
|
|
1607
|
+
...options.destinationTag !== void 0 ? { destinationTag: options.destinationTag } : {}
|
|
1608
|
+
};
|
|
1609
|
+
const result = {
|
|
1610
|
+
scheme: "exact",
|
|
1611
|
+
network: options.testnet ? "xrpl:1" : "xrpl:0",
|
|
1612
|
+
asset: options.currency === "XRP" ? "XRP" : RLUSD_ASSET,
|
|
1613
|
+
amount: options.currency === "XRP" ? xrpToDrops(options.amount) : positiveAmount(options.amount).toFixed(),
|
|
1614
|
+
payTo: options.payTo,
|
|
1615
|
+
maxTimeoutSeconds: options.ttlSeconds ?? 300,
|
|
1616
|
+
extra
|
|
1617
|
+
};
|
|
1618
|
+
validateRequirements(result);
|
|
1619
|
+
return result;
|
|
1620
|
+
}
|
|
1621
|
+
function parseResourceUrl(resource) {
|
|
1622
|
+
const url = new URL(resource);
|
|
1623
|
+
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new Error("A valid HTTP resource URL is required.");
|
|
1624
|
+
return url;
|
|
1625
|
+
}
|
|
1626
|
+
function createPaymentRequired(options, invoiceId = crypto2.randomUUID()) {
|
|
1627
|
+
const url = parseResourceUrl(options.resource);
|
|
1628
|
+
return { x402Version: 2, resource: { url: url.href, description: options.description, mimeType: "application/json" }, accepts: [createPaymentRequirements(options, invoiceId)] };
|
|
1629
|
+
}
|
|
1630
|
+
function x402Middleware(options) {
|
|
1631
|
+
if (!options.challengeSecret && process.env.NODE_ENV === "production") {
|
|
1632
|
+
throw new Error("Configure a stable challengeSecret for production merchant middleware.");
|
|
1633
|
+
}
|
|
1634
|
+
const secret = options.challengeSecret ?? crypto2.randomBytes(32).toString("hex");
|
|
1635
|
+
if (secret.length < 32) throw new Error("challengeSecret must contain at least 32 characters.");
|
|
1636
|
+
createPaymentRequirements(options, "configuration-check");
|
|
1637
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
1638
|
+
const mac = (prefix, resource, method) => crypto2.createHmac("sha256", secret).update(JSON.stringify([prefix, method, resource, requirementsKey(createPaymentRequirements(options, "terms"))])).digest("hex");
|
|
1639
|
+
const middleware = async (req, res, next) => {
|
|
1640
|
+
let resource;
|
|
1641
|
+
try {
|
|
1642
|
+
resource = options.resource ?? `${req.protocol}://${req.get("host")}${req.originalUrl}`;
|
|
1643
|
+
parseResourceUrl(resource);
|
|
1644
|
+
} catch {
|
|
1645
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1646
|
+
return res.status(400).json({ error: "A valid HTTP resource URL is required." });
|
|
1647
|
+
}
|
|
1648
|
+
const method = req.method ?? "GET";
|
|
1649
|
+
const challenge = (error) => {
|
|
1650
|
+
const prefix = `${Date.now()}:${crypto2.randomBytes(16).toString("hex")}`;
|
|
1651
|
+
const required = createPaymentRequired({ ...options, resource }, `${prefix}:${mac(prefix, resource, method)}`);
|
|
1652
|
+
if (error) required.error = error;
|
|
1653
|
+
res.setHeader(PAYMENT_HEADERS.required, encodePaymentHeader(required));
|
|
1654
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1655
|
+
res.setHeader("Access-Control-Expose-Headers", [PAYMENT_HEADERS.required, PAYMENT_HEADERS.response].join(", "));
|
|
1656
|
+
return res.status(402).json(required);
|
|
1657
|
+
};
|
|
1658
|
+
const header = req.headers[PAYMENT_HEADERS.signature.toLowerCase()];
|
|
1659
|
+
if (!header) return challenge();
|
|
1660
|
+
try {
|
|
1661
|
+
if (typeof header !== "string") throw new Error("Invalid payment signature header.");
|
|
1662
|
+
const payload = decodePaymentHeader(header);
|
|
1663
|
+
validateRequirements(payload?.accepted);
|
|
1664
|
+
const invoice = payload.accepted.extra.invoiceId;
|
|
1665
|
+
if (typeof invoice !== "string") throw new Error("Payment challenge is invalid or expired.");
|
|
1666
|
+
const match = /^(\d{13}):([a-f0-9]{32}):([a-f0-9]{64})$/.exec(invoice);
|
|
1667
|
+
const issued = Number(match?.[1]);
|
|
1668
|
+
if (!match || issued > Date.now() || Date.now() - issued > (options.ttlSeconds ?? 300) * 1e3 || !crypto2.timingSafeEqual(Buffer.from(match[3], "hex"), Buffer.from(mac(`${match[1]}:${match[2]}`, resource, method), "hex"))) {
|
|
1669
|
+
throw new Error("Payment challenge is invalid or expired.");
|
|
1670
|
+
}
|
|
1671
|
+
const expected = createPaymentRequirements(options, invoice);
|
|
1672
|
+
validatePayload(payload, expected);
|
|
1673
|
+
if (payload.resource && payload.resource.url !== resource) throw new Error("Payment resource does not match.");
|
|
1674
|
+
let settlement;
|
|
1675
|
+
if (options.facilitator) settlement = await options.facilitator.settle(payload, expected);
|
|
1676
|
+
else {
|
|
1677
|
+
const response = await fetcher(`${(options.facilitatorUrl ?? "https://api.xrpay.it/api/x402").replace(/\/$/, "")}/settle`, {
|
|
1678
|
+
method: "POST",
|
|
1679
|
+
headers: { ...options.facilitatorHeaders, "Content-Type": "application/json" },
|
|
1680
|
+
signal: AbortSignal.timeout(45e3),
|
|
1681
|
+
body: JSON.stringify({ x402Version: 2, paymentPayload: payload, paymentRequirements: expected })
|
|
1682
|
+
});
|
|
1683
|
+
settlement = await response.json();
|
|
1684
|
+
if (!response.ok) throw new Error(settlement.errorReason ?? "Facilitator settlement failed.");
|
|
1685
|
+
}
|
|
1686
|
+
if (!settlement.success || settlement.network !== expected.network || !/^[A-Fa-f0-9]{64}$/.test(settlement.transaction)) {
|
|
1687
|
+
throw new Error(settlement.errorReason ?? "Payment did not settle.");
|
|
1688
|
+
}
|
|
1689
|
+
res.setHeader(PAYMENT_HEADERS.response, encodePaymentHeader(settlement));
|
|
1690
|
+
res.setHeader("Access-Control-Expose-Headers", [PAYMENT_HEADERS.required, PAYMENT_HEADERS.response].join(", "));
|
|
1691
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1692
|
+
req.x402 = settlement;
|
|
1693
|
+
if (options.onSettled) {
|
|
1694
|
+
try {
|
|
1695
|
+
await options.onSettled(settlement, resource);
|
|
1696
|
+
} catch {
|
|
1697
|
+
console.error("[x402] Post-settlement usage recording failed.");
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
} catch (error) {
|
|
1701
|
+
return challenge(error instanceof Error ? error.message : "Payment failed.");
|
|
1702
|
+
}
|
|
1703
|
+
return next();
|
|
1704
|
+
};
|
|
1705
|
+
return (req, res, next) => middleware(req, res, next).catch(next);
|
|
1706
|
+
}
|
|
1707
|
+
export {
|
|
1708
|
+
PAYMENT_HEADERS,
|
|
1709
|
+
RLUSD_ASSET,
|
|
1710
|
+
XrplFacilitator,
|
|
1711
|
+
amountEquals,
|
|
1712
|
+
createPaymentRequired,
|
|
1713
|
+
createPaymentRequirements,
|
|
1714
|
+
decodePaymentHeader,
|
|
1715
|
+
encodePaymentHeader,
|
|
1716
|
+
isRecord,
|
|
1717
|
+
positiveAmount,
|
|
1718
|
+
requirementsKey,
|
|
1719
|
+
validatePayload,
|
|
1720
|
+
validateRequirements,
|
|
1721
|
+
x402Middleware,
|
|
1722
|
+
xrpToDrops
|
|
1723
|
+
};
|