@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 XRPay
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,192 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @xrpay/x402
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Charge for your own APIs, data, or services with XRP or RLUSD using x402 v2 on the XRP Ledger. **You do not need an XRPay account, merchant signup, API key, or a purchase from an XRPay merchant to use the core SDK.** Payments go directly to the XRPL recipient you choose.
|
|
4
|
+
|
|
5
|
+
The package also includes optional XRPay digital-commerce tools for discovering and buying products with managed orders, receipts, and private file delivery.
|
|
6
|
+
|
|
7
|
+
## Which features need an XRPay account?
|
|
8
|
+
|
|
9
|
+
| Feature | XRPay account required? |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| Charge for your own API with `x402Middleware` | No |
|
|
12
|
+
| Pay a compatible exact XRPL x402 endpoint with `X402Client` | No |
|
|
13
|
+
| Use the public facilitator at `https://api.xrpay.it/api/x402` | No account or API key |
|
|
14
|
+
| Browse or buy from the XRPay digital-product catalog | No buyer account or merchant API key |
|
|
15
|
+
| Sell through XRPay's hosted catalog and use its managed orders, receipts, and file delivery | Yes, for the seller |
|
|
16
|
+
|
|
17
|
+
The core SDK is MIT licensed. Payments require XRPL wallets and network fees; Testnet uses test funds. This package implements the exact XRPL x402 scheme for XRP and RLUSD.
|
|
18
|
+
|
|
19
|
+
## Quickstart: charge for your own API
|
|
20
|
+
|
|
21
|
+
Requires Node.js 20+. ESM and CommonJS exports are included. Create an empty project and install:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm init -y
|
|
25
|
+
npm install @xrpay/x402 express
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Save this as `paid-api.mjs`:
|
|
29
|
+
|
|
30
|
+
```js
|
|
31
|
+
// npm install @xrpay/x402 express
|
|
32
|
+
// Uses XRP Testnet. No XRPay account, API key, or product listing is required.
|
|
33
|
+
import express from "express";
|
|
34
|
+
import { x402Middleware } from "@xrpay/x402";
|
|
35
|
+
|
|
36
|
+
const payTo = process.env.XRPL_RECIPIENT_ADDRESS;
|
|
37
|
+
const challengeSecret = process.env.X402_CHALLENGE_SECRET;
|
|
38
|
+
if (!payTo || !challengeSecret) {
|
|
39
|
+
throw new Error("Set XRPL_RECIPIENT_ADDRESS and X402_CHALLENGE_SECRET (at least 32 characters).");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const app = express();
|
|
43
|
+
app.get("/api/hello", x402Middleware({
|
|
44
|
+
payTo,
|
|
45
|
+
amount: "0.001", // XRP per request, paid directly to your wallet.
|
|
46
|
+
currency: "XRP",
|
|
47
|
+
testnet: true,
|
|
48
|
+
challengeSecret,
|
|
49
|
+
facilitatorUrl: "https://api.xrpay.it/api/x402", // Public; no API key.
|
|
50
|
+
}), (_req, res) => res.json({ message: "Hello from your paid API!" }));
|
|
51
|
+
|
|
52
|
+
const port = Number(process.env.PORT ?? 3000);
|
|
53
|
+
app.listen(port, "127.0.0.1", () => {
|
|
54
|
+
console.log(`Paid API: http://127.0.0.1:${port}/api/hello (0.001 Testnet XRP)`);
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Generate a receiving wallet with the [XRPL Testnet faucet](https://xrpl.org/resources/dev-tools/xrp-faucets), select **Testnet**, and use its classic address below. The API server needs only the receiving address, not that wallet's seed.
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
export XRPL_RECIPIENT_ADDRESS="rYOUR_FUNDED_TESTNET_ADDRESS"
|
|
62
|
+
export X402_CHALLENGE_SECRET="$(openssl rand -hex 32)"
|
|
63
|
+
node paid-api.mjs
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The same runnable file is included at `node_modules/@xrpay/x402/examples/paid-api.mjs`. `X402_CHALLENGE_SECRET` is a random secret you generate locally to authenticate payment challenges; it is **not an XRPay API key**. Store it privately and reuse it across server processes and restarts.
|
|
67
|
+
|
|
68
|
+
In another terminal:
|
|
69
|
+
|
|
70
|
+
```sh
|
|
71
|
+
curl -i http://127.0.0.1:3000/api/hello
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
An unpaid request returns **HTTP 402** with `PAYMENT-REQUIRED` and the exact payment terms. A compatible agent signs those terms and retries with `PAYMENT-SIGNATURE`. The middleware settles through the public facilitator, then returns **HTTP 200**, the API result, and a `PAYMENT-RESPONSE` receipt. For a runnable payment flow, follow [the agent client example](https://www.xrpay.it/docs/x402#agent).
|
|
75
|
+
|
|
76
|
+
You host the API and control its response. No XRPay product or merchant record is created, and these standalone payments do not create hosted storefront orders or file-delivery entitlements. Those are optional commerce features described below. You can also supply your own `XrplFacilitator` instance through the middleware's `facilitator` option.
|
|
77
|
+
|
|
78
|
+
The example binds to localhost and uses Testnet. For deployment, serve your API over HTTPS and configure the public resource URL when running behind a proxy. Use `testnet: false` and Mainnet wallets deliberately for real XRP payments. RLUSD requires the exact issuer and matching payer/recipient trust lines on the chosen network.
|
|
79
|
+
|
|
80
|
+
## Buy a digital product
|
|
81
|
+
|
|
82
|
+
This optional flow buys from XRPay merchants. Buyers do not need an XRPay account.
|
|
83
|
+
|
|
84
|
+
```js
|
|
85
|
+
import { Client, Wallet } from "xrpl";
|
|
86
|
+
import { XRPayCommerceClient, createRecoveryCredentials } from "@xrpay/x402/commerce";
|
|
87
|
+
|
|
88
|
+
const ledger = new Client("wss://s.altnet.rippletest.net:51233");
|
|
89
|
+
await ledger.connect();
|
|
90
|
+
const wallet = Wallet.fromSeed(process.env.XRPL_WALLET_SEED);
|
|
91
|
+
const commerce = new XRPayCommerceClient({
|
|
92
|
+
payment: {
|
|
93
|
+
wallet, ledgerClient: ledger,
|
|
94
|
+
network: "xrpl:1", currency: "XRP",
|
|
95
|
+
maxAmount: "1", maxTotalAmount: "5",
|
|
96
|
+
allowedRecipients: ["YOUR_MERCHANT_CLASSIC_ADDRESS"],
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
const catalog = await commerce.discover({ network: "xrpl:1", query: "research" });
|
|
100
|
+
const product = catalog.products[0];
|
|
101
|
+
if (!product) throw new Error("No matching product");
|
|
102
|
+
|
|
103
|
+
const credentials = createRecoveryCredentials();
|
|
104
|
+
await savePrivately(credentials); // Your durable storage; never log these tokens.
|
|
105
|
+
const { purchase, handle } = await commerce.createPurchase(product.id, {
|
|
106
|
+
customerEmail: "buyer@example.com", payerAddress: wallet.address,
|
|
107
|
+
}, credentials);
|
|
108
|
+
await savePrivately(handle);
|
|
109
|
+
console.log(purchase.quote); // Review the exact price before authorizing payment.
|
|
110
|
+
|
|
111
|
+
const paid = await commerce.pay(handle, savePrivately);
|
|
112
|
+
if (paid.status === "paid") {
|
|
113
|
+
const receipt = await commerce.receipt(handle);
|
|
114
|
+
const { bytes, sha256 } = await commerce.download(handle);
|
|
115
|
+
}
|
|
116
|
+
await ledger.disconnect();
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`savePrivately` is an application-supplied function that durably stores its argument. `pay` waits for it before sending any signed authorization. A runnable example with private local storage is in `examples/buy-digital-product.mjs`.
|
|
120
|
+
|
|
121
|
+
Amounts in SDK spending caps are human XRP/RLUSD amounts. Caps cover authorizations within that client instance; applications with several processes or restarts must persist and enforce their own aggregate spending budget. RLUSD requires the exact issuer for the chosen network. Mainnet uses `xrpl:0`; Testnet uses `xrpl:1` and has no monetary value. Choose both the network and a trusted recipient explicitly.
|
|
122
|
+
|
|
123
|
+
### Recovery and delivery
|
|
124
|
+
|
|
125
|
+
- Save recovery credentials **before** creating a purchase. Retrying the same listing, buyer, credentials and idempotency key returns the same purchase.
|
|
126
|
+
- Save the handle before paying. The checkpoint receives the exact signed payment before submission. A retry resends that authorization; it does not sign a replacement.
|
|
127
|
+
- After a timeout, call `commerce.recover(handle)`. If it is still `settling`, call `pay(handle, savePrivately)` to retry the saved authorization. Never create another purchase to recover an uncertain payment.
|
|
128
|
+
- `paid` includes an order ID, receipt URL and download URL. These require the handle's bearer token. Possession of the token grants access; keep it out of URLs, logs and prompts.
|
|
129
|
+
- Downloads are available immediately after confirmation and are verified against the purchased file's SHA-256 and byte length. Replacement files and later price changes do not alter prior purchases.
|
|
130
|
+
- A receipt is returned as JSON; customer email is recorded on the order and receipt. This flow does not send email automatically.
|
|
131
|
+
- Files are untrusted merchant content. Downloading does not authorize executing them.
|
|
132
|
+
|
|
133
|
+
## MCP server
|
|
134
|
+
|
|
135
|
+
These seven tools cover XRPay hosted digital commerce. To charge for your own API independently, use `x402Middleware` from the quickstart above.
|
|
136
|
+
|
|
137
|
+
```sh
|
|
138
|
+
npx -y @xrpay/x402
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
For an MCP client:
|
|
142
|
+
|
|
143
|
+
```json
|
|
144
|
+
{
|
|
145
|
+
"mcpServers": {
|
|
146
|
+
"xrpay-commerce": {
|
|
147
|
+
"command": "npx",
|
|
148
|
+
"args": ["-y", "@xrpay/x402"]
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
Tools: `discover_digital_products`, `create_digital_purchase`, `pay_digital_purchase`, `get_digital_purchase`, `get_digital_receipt`, `download_digital_product`, `list_digital_purchases`.
|
|
155
|
+
|
|
156
|
+
The MCP server prepares quotes and submits payments signed by your separate XRPL wallet integration. It never requests a seed or private key. The SDK above can sign locally and complete the flow automatically within its spending limits.
|
|
157
|
+
|
|
158
|
+
Recovery records are stored privately in `~/.xrpay/agent-commerce`; downloaded files are placed in its `downloads` directory. Back up this state to retain access. Optional environment variables: `XRPAY_COMMERCE_ORIGIN` and `XRPAY_COMMERCE_STATE_DIR`.
|
|
159
|
+
|
|
160
|
+
## Merchant setup for hosted commerce
|
|
161
|
+
|
|
162
|
+
An XRPay merchant account is required for this hosted catalog and fulfillment integration. It is not required for the standalone payment SDK.
|
|
163
|
+
|
|
164
|
+
In XRPay, open **Agent payments → Digital products** (`/dashboard/x402/products`). Create and publish a fixed-price digital product in a live storefront, turn off inventory tracking, upload the private delivery file, and enable agent availability. Each file can be up to 10 MiB; private file storage is capped at 100 MiB per merchant, including retained versions.
|
|
165
|
+
|
|
166
|
+
Only opted-in products are discoverable. Sales use the current sale price and configured product/store tax. Quotes lock that total and its exchange rate for five minutes. Coupons, quantity bundles, inventory-limited licenses and shipping are not supported by this flow. Testnet and Mainnet listings are separate. Completed purchases appear as delivered storefront orders with a confirmed direct XRPL transaction.
|
|
167
|
+
|
|
168
|
+
## HTTP API
|
|
169
|
+
|
|
170
|
+
Base: `https://api.xrpay.it`.
|
|
171
|
+
|
|
172
|
+
| Method | Path | Purpose |
|
|
173
|
+
| --- | --- | --- |
|
|
174
|
+
| GET | `/.well-known/xrpay-commerce.json` | Integration discovery |
|
|
175
|
+
| GET | `/api/x402/products` | Catalog: `network`, `merchant`, `q`, `after`, `limit` |
|
|
176
|
+
| POST | `/api/x402/products/:id/purchases` | Quote; JSON `customerEmail`, `payerAddress` |
|
|
177
|
+
| POST | `/api/x402/purchases/:id` | 402 challenge, then payment submission |
|
|
178
|
+
| GET | `/api/x402/purchases/:id` | Recover status and order |
|
|
179
|
+
| GET | `/api/x402/purchases/:id/receipt` | Paid receipt |
|
|
180
|
+
| GET | `/api/x402/purchases/:id/download` | Private download |
|
|
181
|
+
|
|
182
|
+
Create requires `Authorization: Bearer <random-token>` and `Idempotency-Key`. Generate at least 32 random bytes for the token, encoded as hex or base64url. The same bearer token authenticates all purchase operations. Only its SHA-256 is stored by XRPay. Signed retries add `PAYMENT-SIGNATURE`; 402 responses include `PAYMENT-REQUIRED`; paid responses include `PAYMENT-RESPONSE`. A 202 means the recorded payment still needs confirmation, not that it failed. OPTIONS requests support browser CORS.
|
|
183
|
+
|
|
184
|
+
## Payment SDK and facilitator
|
|
185
|
+
|
|
186
|
+
Use the [standalone API quickstart](#quickstart-charge-for-your-own-api) above for your own service. `X402Client` from `@xrpay/x402/client` can pay compatible exact XRPL x402 resources with explicit network, asset, recipient and spending controls. `@xrpay/x402/protocol` exports wire types and header helpers. Wallet keys stay in the buyer's process.
|
|
187
|
+
|
|
188
|
+
The public facilitator is `https://api.xrpay.it/api/x402`, with `/supported`, `/verify` and `/settle`. **These routes need no XRPay account or API key.** The optional authenticated merchant variants under `/api/v1/x402` require XRPay credentials and bind settlement to the merchant wallet and network.
|
|
189
|
+
|
|
190
|
+
## Development
|
|
191
|
+
|
|
192
|
+
From the XRPay repository: `npm run build:x402`, then `npm run test:x402`. To run database-backed commerce tests, set `X402_TEST_DATABASE_URL` to an isolated local PostgreSQL database initialized from `prisma/schema.prisma`. Package builds include declarations, ESM, CommonJS and the MCP executable. MIT licensed.
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var XRPayX402=(()=>{var we=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var ke=(u,p)=>{for(var x in p)we(u,x,{get:p[x],enumerable:!0})},qe=(u,p,x,E)=>{if(p&&typeof p=="object"||typeof p=="function")for(let d of Ie(p))!_e.call(u,d)&&d!==x&&we(u,d,{get:()=>p[d],enumerable:!(E=Se(p,d))||E.enumerable});return u};var De=u=>qe(we({},"__esModule",{value:!0}),u);var Xe={};ke(Xe,{PAYMENT_HEADERS:()=>se,RLUSD_ASSET:()=>he,X402Client:()=>Pe,amountEquals:()=>Ce,decodePaymentHeader:()=>pe,encodePaymentHeader:()=>Ae,isRecord:()=>Z,positiveAmount:()=>U,requirementsKey:()=>Re,validatePayload:()=>Ue,validateRequirements:()=>ae,xrpToDrops:()=>Me});var Le=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,xe=Math.ceil,H=Math.floor,v="[BigNumber Error] ",Ne=v+"Number primitive has more than 15 significant digits: ",W=1e14,y=14,ye=9007199254740991,Ee=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],ee=1e7,D=1e9;function Te(u){var p,x,E,d=g.prototype={constructor:g,toString:null,valueOf:null},I=new g(1),N=20,O=4,L=-7,P=21,V=-1e7,X=1e7,Y=!1,te=1,C=0,j={prefix:"",groupSize:3,secondaryGroupSize:0,groupSeparator:",",decimalSeparator:".",fractionGroupSize:0,fractionGroupSeparator:"\xA0",suffix:""},b="0123456789abcdefghijklmnopqrstuvwxyz",ne=!0;function g(e,t){var r,f,i,o,l,n,s,c,a=this;if(!(a instanceof g))return new g(e,t);if(t==null){if(e&&e._isBigNumber===!0){a.s=e.s,!e.c||e.e>X?a.c=a.e=null:e.e<V?a.c=[a.e=0]:(a.e=e.e,a.c=e.c.slice());return}if((n=typeof e=="number")&&e*0==0){if(a.s=1/e<0?(e=-e,-1):1,e===~~e){for(o=0,l=e;l>=10;l/=10,o++);o>X?a.c=a.e=null:(a.e=o,a.c=[e]);return}c=String(e)}else{if(!Le.test(c=String(e)))return E(a,c,n);a.s=c.charCodeAt(0)==45?(c=c.slice(1),-1):1}(o=c.indexOf("."))>-1&&(c=c.replace(".","")),(l=c.search(/e/i))>0?(o<0&&(o=l),o+=+c.slice(l+1),c=c.substring(0,l)):o<0&&(o=c.length)}else{if(S(t,2,b.length,"Base"),t==10&&ne)return a=new g(e),F(a,N+a.e+1,O);if(c=String(e),n=typeof e=="number"){if(e*0!=0)return E(a,c,n,t);if(a.s=1/e<0?(c=c.slice(1),-1):1,g.DEBUG&&c.replace(/^0\.0*|\./,"").length>15)throw Error(Ne+e)}else a.s=c.charCodeAt(0)===45?(c=c.slice(1),-1):1;for(r=b.slice(0,t),o=l=0,s=c.length;l<s;l++)if(r.indexOf(f=c.charAt(l))<0){if(f=="."){if(l>o){o=s;continue}}else if(!i&&(c==c.toUpperCase()&&(c=c.toLowerCase())||c==c.toLowerCase()&&(c=c.toUpperCase()))){i=!0,l=-1,o=0;continue}return E(a,String(e),n,t)}n=!1,c=x(c,t,10,a.s),(o=c.indexOf("."))>-1?c=c.replace(".",""):o=c.length}for(l=0;c.charCodeAt(l)===48;l++);for(s=c.length;c.charCodeAt(--s)===48;);if(c=c.slice(l,++s)){if(s-=l,n&&g.DEBUG&&s>15&&(e>ye||e!==H(e)))throw Error(Ne+a.s*e);if((o=o-l-1)>X)a.c=a.e=null;else if(o<V)a.c=[a.e=0];else{if(a.e=o,a.c=[],l=(o+1)%y,o<0&&(l+=y),l<s){for(l&&a.c.push(+c.slice(0,l)),s-=y;l<s;)a.c.push(+c.slice(l,l+=y));l=y-(c=c.slice(l)).length}else l-=s;for(;l--;c+="0");a.c.push(+c)}}else a.c=[a.e=0]}g.clone=Te,g.ROUND_UP=0,g.ROUND_DOWN=1,g.ROUND_CEIL=2,g.ROUND_FLOOR=3,g.ROUND_HALF_UP=4,g.ROUND_HALF_DOWN=5,g.ROUND_HALF_EVEN=6,g.ROUND_HALF_CEIL=7,g.ROUND_HALF_FLOOR=8,g.EUCLID=9,g.config=g.set=function(e){var t,r;if(e!=null)if(typeof e=="object"){if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(r=e[t],S(r,0,D,t),N=r),e.hasOwnProperty(t="ROUNDING_MODE")&&(r=e[t],S(r,0,8,t),O=r),e.hasOwnProperty(t="EXPONENTIAL_AT")&&(r=e[t],r&&r.pop?(S(r[0],-D,0,t),S(r[1],0,D,t),L=r[0],P=r[1]):(S(r,-D,D,t),L=-(P=r<0?-r:r))),e.hasOwnProperty(t="RANGE"))if(r=e[t],r&&r.pop)S(r[0],-D,-1,t),S(r[1],1,D,t),V=r[0],X=r[1];else if(S(r,-D,D,t),r)V=-(X=r<0?-r:r);else throw Error(v+t+" cannot be zero: "+r);if(e.hasOwnProperty(t="CRYPTO"))if(r=e[t],r===!!r)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))Y=r;else throw Y=!r,Error(v+"crypto unavailable");else Y=r;else throw Error(v+t+" not true or false: "+r);if(e.hasOwnProperty(t="MODULO_MODE")&&(r=e[t],S(r,0,9,t),te=r),e.hasOwnProperty(t="POW_PRECISION")&&(r=e[t],S(r,0,D,t),C=r),e.hasOwnProperty(t="FORMAT"))if(r=e[t],typeof r=="object")j=r;else throw Error(v+t+" not an object: "+r);if(e.hasOwnProperty(t="ALPHABET"))if(r=e[t],typeof r=="string"&&!/^.?$|[+\-.\s]|(.).*\1/.test(r))ne=r.slice(0,10)=="0123456789",b=r;else throw Error(v+t+" invalid: "+r)}else throw Error(v+"Object expected: "+e);return{DECIMAL_PLACES:N,ROUNDING_MODE:O,EXPONENTIAL_AT:[L,P],RANGE:[V,X],CRYPTO:Y,MODULO_MODE:te,POW_PRECISION:C,FORMAT:j,ALPHABET:b}},g.isBigNumber=function(e){if(!e||e._isBigNumber!==!0)return!1;if(!g.DEBUG)return!0;var t,r,f=e.c,i=e.e,o=e.s;e:if({}.toString.call(f)=="[object Array]"){if((o===1||o===-1)&&i>=-D&&i<=D&&i===H(i)){if(f[0]===0){if(i===0&&f.length===1)return!0;break e}if(t=(i+1)%y,t<1&&(t+=y),String(f[0]).length==t){for(t=0;t<f.length;t++)if(r=f[t],r<0||r>=W||r!==H(r))break e;if(r!==0)return!0}}}else if(f===null&&i===null&&(o===null||o===1||o===-1))return!0;throw Error(v+"Invalid BigNumber: "+e)},g.maximum=g.max=function(){return fe(arguments,-1)},g.minimum=g.min=function(){return fe(arguments,1)},g.random=(function(){var e=9007199254740992,t=Math.random()*e&2097151?function(){return H(Math.random()*e)}:function(){return(Math.random()*1073741824|0)*8388608+(Math.random()*8388608|0)};return function(r){var f,i,o,l,n,s=0,c=[],a=new g(I);if(r==null?r=N:S(r,0,D),l=xe(r/y),Y)if(crypto.getRandomValues){for(f=crypto.getRandomValues(new Uint32Array(l*=2));s<l;)n=f[s]*131072+(f[s+1]>>>11),n>=9e15?(i=crypto.getRandomValues(new Uint32Array(2)),f[s]=i[0],f[s+1]=i[1]):(c.push(n%1e14),s+=2);s=l/2}else if(crypto.randomBytes){for(f=crypto.randomBytes(l*=7);s<l;)n=(f[s]&31)*281474976710656+f[s+1]*1099511627776+f[s+2]*4294967296+f[s+3]*16777216+(f[s+4]<<16)+(f[s+5]<<8)+f[s+6],n>=9e15?crypto.randomBytes(7).copy(f,s):(c.push(n%1e14),s+=7);s=l/7}else throw Y=!1,Error(v+"crypto unavailable");if(!Y)for(;s<l;)n=t(),n<9e15&&(c[s++]=n%1e14);for(l=c[--s],r%=y,l&&r&&(n=Ee[y-r],c[s]=H(l/n)*n);c[s]===0;c.pop(),s--);if(s<0)c=[o=0];else{for(o=-1;c[0]===0;c.splice(0,1),o-=y);for(s=1,n=c[0];n>=10;n/=10,s++);s<y&&(o-=y-s)}return a.e=o,a.c=c,a}})(),g.sum=function(){for(var e=1,t=arguments,r=new g(t[0]);e<t.length;)r=r.plus(t[e++]);return r},x=(function(){var e="0123456789";function t(r,f,i,o){for(var l,n=[0],s,c=0,a=r.length;c<a;){for(s=n.length;s--;n[s]*=f);for(n[0]+=o.indexOf(r.charAt(c++)),l=0;l<n.length;l++)n[l]>i-1&&(n[l+1]==null&&(n[l+1]=0),n[l+1]+=n[l]/i|0,n[l]%=i)}return n.reverse()}return function(r,f,i,o,l){var n,s,c,a,h,m,w,A,_=r.indexOf("."),q=N,R=O;for(_>=0&&(a=C,C=0,r=r.replace(".",""),A=new g(f),m=A.pow(r.length-_),C=a,A.c=t(K(z(m.c),m.e,"0"),10,i,e),A.e=A.c.length),w=t(r,f,i,l?(n=b,e):(n=e,b)),c=a=w.length;w[--a]==0;w.pop());if(!w[0])return n.charAt(0);if(_<0?--c:(m.c=w,m.e=c,m.s=o,m=p(m,A,q,R,i),w=m.c,h=m.r,c=m.e),s=c+q+1,_=w[s],a=i/2,h=h||s<0||w[s+1]!=null,h=R<4?(_!=null||h)&&(R==0||R==(m.s<0?3:2)):_>a||_==a&&(R==4||h||R==6&&w[s-1]&1||R==(m.s<0?8:7)),s<1||!w[0])r=h?K(n.charAt(1),-q,n.charAt(0)):n.charAt(0);else{if(w.length=s,h)for(--i;++w[--s]>i;)w[s]=0,s||(++c,w=[1].concat(w));for(a=w.length;!w[--a];);for(_=0,r="";_<=a;r+=n.charAt(w[_++]));r=K(r,c,n.charAt(0))}return r}})(),p=(function(){function e(f,i,o){var l,n,s,c,a=0,h=f.length,m=i%ee,w=i/ee|0;for(f=f.slice();h--;)s=f[h]%ee,c=f[h]/ee|0,l=w*s+c*m,n=m*s+l%ee*ee+a,a=(n/o|0)+(l/ee|0)+w*c,f[h]=n%o;return a&&(f=[a].concat(f)),f}function t(f,i,o,l){var n,s;if(o!=l)s=o>l?1:-1;else for(n=s=0;n<o;n++)if(f[n]!=i[n]){s=f[n]>i[n]?1:-1;break}return s}function r(f,i,o,l){for(var n=0;o--;)f[o]-=n,n=f[o]<i[o]?1:0,f[o]=n*l+f[o]-i[o];for(;!f[0]&&f.length>1;f.splice(0,1));}return function(f,i,o,l,n){var s,c,a,h,m,w,A,_,q,R,T,B,ce,ge,me,J,oe,G=f.s==i.s?1:-1,M=f.c,k=i.c;if(!M||!M[0]||!k||!k[0])return new g(!f.s||!i.s||(M?k&&M[0]==k[0]:!k)?NaN:M&&M[0]==0||!k?G*0:G/0);for(_=new g(G),q=_.c=[],c=f.e-i.e,G=o+c+1,n||(n=W,c=$(f.e/y)-$(i.e/y),G=G/y|0),a=0;k[a]==(M[a]||0);a++);if(k[a]>(M[a]||0)&&c--,G<0)q.push(1),h=!0;else{for(ge=M.length,J=k.length,a=0,G+=2,m=H(n/(k[0]+1)),m>1&&(k=e(k,m,n),M=e(M,m,n),J=k.length,ge=M.length),ce=J,R=M.slice(0,J),T=R.length;T<J;R[T++]=0);oe=k.slice(),oe=[0].concat(oe),me=k[0],k[1]>=n/2&&me++;do{if(m=0,s=t(k,R,J,T),s<0){if(B=R[0],J!=T&&(B=B*n+(R[1]||0)),m=H(B/me),m>1)for(m>=n&&(m=n-1),w=e(k,m,n),A=w.length,T=R.length;t(w,R,A,T)==1;)m--,r(w,J<A?oe:k,A,n),A=w.length,s=1;else m==0&&(s=m=1),w=k.slice(),A=w.length;if(A<T&&(w=[0].concat(w)),r(R,w,T,n),T=R.length,s==-1)for(;t(k,R,J,T)<1;)m++,r(R,J<T?oe:k,T,n),T=R.length}else s===0&&(m++,R=[0]);q[a++]=m,R[0]?R[T++]=M[ce]||0:(R=[M[ce]],T=1)}while((ce++<ge||R[0]!=null)&&G--);h=R[0]!=null,q[0]||q.splice(0,1)}if(n==W){for(a=1,G=q[0];G>=10;G/=10,a++);F(_,o+(_.e=a+c*y-1)+1,l,h)}else _.e=c,_.r=+h;return _}})();function ie(e,t,r,f){var i,o,l,n,s;if(r==null?r=O:S(r,0,8),!e.c)return e.toString();if(i=e.c[0],l=e.e,t==null)s=z(e.c),s=f==1||f==2&&(l<=L||l>=P)?ue(s,l):K(s,l,"0");else if(e=F(new g(e),t,r),o=e.e,s=z(e.c),n=s.length,f==1||f==2&&(t<=o||o<=L)){for(;n<t;s+="0",n++);s=ue(s,o)}else if(t-=l,s=K(s,o,"0"),o+1>n){if(--t>0)for(s+=".";t--;s+="0");}else if(t+=o-n,t>0)for(o+1==n&&(s+=".");t--;s+="0");return e.s<0&&i?"-"+s:s}function fe(e,t){for(var r,f,i=1,o=new g(e[0]);i<e.length;i++)f=new g(e[i]),(!f.s||(r=re(o,f))===t||r===0&&o.s===t)&&(o=f);return o}function de(e,t,r){for(var f=1,i=t.length;!t[--i];t.pop());for(i=t[0];i>=10;i/=10,f++);return(r=f+r*y-1)>X?e.c=e.e=null:r<V?e.c=[e.e=0]:(e.e=r,e.c=t),e}E=(function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,t=/^([^.]+)\.$/,r=/^\.([^.]+)$/,f=/^-?(Infinity|NaN)$/,i=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,l,n,s){var c,a=n?l:l.replace(i,"");if(f.test(a))o.s=isNaN(a)?null:a<0?-1:1;else{if(!n&&(a=a.replace(e,function(h,m,w){return c=(w=w.toLowerCase())=="x"?16:w=="b"?2:8,!s||s==c?m:h}),s&&(c=s,a=a.replace(t,"$1").replace(r,"0.$1")),l!=a))return new g(a,c);if(g.DEBUG)throw Error(v+"Not a"+(s?" base "+s:"")+" number: "+l);o.s=null}o.c=o.e=null}})();function F(e,t,r,f){var i,o,l,n,s,c,a,h=e.c,m=Ee;if(h){e:{for(i=1,n=h[0];n>=10;n/=10,i++);if(o=t-i,o<0)o+=y,l=t,s=h[c=0],a=H(s/m[i-l-1]%10);else if(c=xe((o+1)/y),c>=h.length)if(f){for(;h.length<=c;h.push(0));s=a=0,i=1,o%=y,l=o-y+1}else break e;else{for(s=n=h[c],i=1;n>=10;n/=10,i++);o%=y,l=o-y+i,a=l<0?0:H(s/m[i-l-1]%10)}if(f=f||t<0||h[c+1]!=null||(l<0?s:s%m[i-l-1]),f=r<4?(a||f)&&(r==0||r==(e.s<0?3:2)):a>5||a==5&&(r==4||f||r==6&&(o>0?l>0?s/m[i-l]:0:h[c-1])%10&1||r==(e.s<0?8:7)),t<1||!h[0])return h.length=0,f?(t-=e.e+1,h[0]=m[(y-t%y)%y],e.e=-t||0):h[0]=e.e=0,e;if(o==0?(h.length=c,n=1,c--):(h.length=c+1,n=m[y-o],h[c]=l>0?H(s/m[i-l]%m[l])*n:0),f)for(;;)if(c==0){for(o=1,l=h[0];l>=10;l/=10,o++);for(l=h[0]+=n,n=1;l>=10;l/=10,n++);o!=n&&(e.e++,h[0]==W&&(h[0]=1));break}else{if(h[c]+=n,h[c]!=W)break;h[c--]=0,n=1}for(o=h.length;h[--o]===0;h.pop());}e.e>X?e.c=e.e=null:e.e<V&&(e.c=[e.e=0])}return e}function Q(e){var t,r=e.e;return r===null?e.toString():(t=z(e.c),t=r<=L||r>=P?ue(t,r):K(t,r,"0"),e.s<0?"-"+t:t)}return d.absoluteValue=d.abs=function(){var e=new g(this);return e.s<0&&(e.s=1),e},d.comparedTo=function(e,t){return re(this,new g(e,t))},d.decimalPlaces=d.dp=function(e,t){var r,f,i,o=this;if(e!=null)return S(e,0,D),t==null?t=O:S(t,0,8),F(new g(o),e+o.e+1,t);if(!(r=o.c))return null;if(f=((i=r.length-1)-$(this.e/y))*y,i=r[i])for(;i%10==0;i/=10,f--);return f<0&&(f=0),f},d.dividedBy=d.div=function(e,t){return p(this,new g(e,t),N,O)},d.dividedToIntegerBy=d.idiv=function(e,t){return p(this,new g(e,t),0,1)},d.exponentiatedBy=d.pow=function(e,t){var r,f,i,o,l,n,s,c,a,h=this;if(e=new g(e),e.c&&!e.isInteger())throw Error(v+"Exponent not an integer: "+Q(e));if(t!=null&&(t=new g(t)),n=e.e>14,!h.c||!h.c[0]||h.c[0]==1&&!h.e&&h.c.length==1||!e.c||!e.c[0])return a=new g(Math.pow(+Q(h),n?e.s*(2-le(e)):+Q(e))),t?a.mod(t):a;if(s=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new g(NaN);f=!s&&h.isInteger()&&t.isInteger(),f&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(h.e==0?h.c[0]>1||n&&h.c[1]>=24e7:h.c[0]<8e13||n&&h.c[0]<=9999975e7)))return o=h.s<0&&le(e)?-0:0,h.e>-1&&(o=1/o),new g(s?1/o:o);C&&(o=xe(C/y+2))}for(n?(r=new g(.5),s&&(e.s=1),c=le(e)):(i=Math.abs(+Q(e)),c=i%2),a=new g(I);;){if(c){if(a=a.times(h),!a.c)break;o?a.c.length>o&&(a.c.length=o):f&&(a=a.mod(t))}if(i){if(i=H(i/2),i===0)break;c=i%2}else if(e=e.times(r),F(e,e.e+1,1),e.e>14)c=le(e);else{if(i=+Q(e),i===0)break;c=i%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):f&&(h=h.mod(t))}return f?a:(s&&(a=I.div(a)),t?a.mod(t):o?F(a,C,O,l):a)},d.integerValue=function(e){var t=new g(this);return e==null?e=O:S(e,0,8),F(t,t.e+1,e)},d.isEqualTo=d.eq=function(e,t){return re(this,new g(e,t))===0},d.isFinite=function(){return!!this.c},d.isGreaterThan=d.gt=function(e,t){return re(this,new g(e,t))>0},d.isGreaterThanOrEqualTo=d.gte=function(e,t){return(t=re(this,new g(e,t)))===1||t===0},d.isInteger=function(){return!!this.c&&$(this.e/y)>this.c.length-2},d.isLessThan=d.lt=function(e,t){return re(this,new g(e,t))<0},d.isLessThanOrEqualTo=d.lte=function(e,t){return(t=re(this,new g(e,t)))===-1||t===0},d.isNaN=function(){return!this.s},d.isNegative=function(){return this.s<0},d.isPositive=function(){return this.s>0},d.isZero=function(){return!!this.c&&this.c[0]==0},d.minus=function(e,t){var r,f,i,o,l=this,n=l.s;if(e=new g(e,t),t=e.s,!n||!t)return new g(NaN);if(n!=t)return e.s=-t,l.plus(e);var s=l.e/y,c=e.e/y,a=l.c,h=e.c;if(!s||!c){if(!a||!h)return a?(e.s=-t,e):new g(h?l:NaN);if(!a[0]||!h[0])return h[0]?(e.s=-t,e):new g(a[0]?l:O==3?-0:0)}if(s=$(s),c=$(c),a=a.slice(),n=s-c){for((o=n<0)?(n=-n,i=a):(c=s,i=h),i.reverse(),t=n;t--;i.push(0));i.reverse()}else for(f=(o=(n=a.length)<(t=h.length))?n:t,n=t=0;t<f;t++)if(a[t]!=h[t]){o=a[t]<h[t];break}if(o&&(i=a,a=h,h=i,e.s=-e.s),t=(f=h.length)-(r=a.length),t>0)for(;t--;a[r++]=0);for(t=W-1;f>n;){if(a[--f]<h[f]){for(r=f;r&&!a[--r];a[r]=t);--a[r],a[f]+=W}a[f]-=h[f]}for(;a[0]==0;a.splice(0,1),--c);return a[0]?de(e,a,c):(e.s=O==3?-1:1,e.c=[e.e=0],e)},d.modulo=d.mod=function(e,t){var r,f,i=this;return e=new g(e,t),!i.c||!e.s||e.c&&!e.c[0]?new g(NaN):!e.c||i.c&&!i.c[0]?new g(i):(te==9?(f=e.s,e.s=1,r=p(i,e,0,3),e.s=f,r.s*=f):r=p(i,e,0,te),e=i.minus(r.times(e)),!e.c[0]&&te==1&&(e.s=i.s),e)},d.multipliedBy=d.times=function(e,t){var r,f,i,o,l,n,s,c,a,h,m,w,A,_,q,R=this,T=R.c,B=(e=new g(e,t)).c;if(!T||!B||!T[0]||!B[0])return!R.s||!e.s||T&&!T[0]&&!B||B&&!B[0]&&!T?e.c=e.e=e.s=null:(e.s*=R.s,!T||!B?e.c=e.e=null:(e.c=[0],e.e=0)),e;for(f=$(R.e/y)+$(e.e/y),e.s*=R.s,s=T.length,h=B.length,s<h&&(A=T,T=B,B=A,i=s,s=h,h=i),i=s+h,A=[];i--;A.push(0));for(_=W,q=ee,i=h;--i>=0;){for(r=0,m=B[i]%q,w=B[i]/q|0,l=s,o=i+l;o>i;)c=T[--l]%q,a=T[l]/q|0,n=w*c+a*m,c=m*c+n%q*q+A[o]+r,r=(c/_|0)+(n/q|0)+w*a,A[o--]=c%_;A[o]=r}return r?++f:A.splice(0,1),de(e,A,f)},d.negated=function(){var e=new g(this);return e.s=-e.s||null,e},d.plus=function(e,t){var r,f=this,i=f.s;if(e=new g(e,t),t=e.s,!i||!t)return new g(NaN);if(i!=t)return e.s=-t,f.minus(e);var o=f.e/y,l=e.e/y,n=f.c,s=e.c;if(!o||!l){if(!n||!s)return new g(i/0);if(!n[0]||!s[0])return s[0]?e:new g(n[0]?f:i*0)}if(o=$(o),l=$(l),n=n.slice(),i=o-l){for(i>0?(l=o,r=s):(i=-i,r=n),r.reverse();i--;r.push(0));r.reverse()}for(i=n.length,t=s.length,i-t<0&&(r=s,s=n,n=r,t=i),i=0;t;)i=(n[--t]=n[t]+s[t]+i)/W|0,n[t]=W===n[t]?0:n[t]%W;return i&&(n=[i].concat(n),++l),de(e,n,l)},d.precision=d.sd=function(e,t){var r,f,i,o=this;if(e!=null&&e!==!!e)return S(e,1,D),t==null?t=O:S(t,0,8),F(new g(o),e,t);if(!(r=o.c))return null;if(i=r.length-1,f=i*y+1,i=r[i]){for(;i%10==0;i/=10,f--);for(i=r[0];i>=10;i/=10,f++);}return e&&o.e+1>f&&(f=o.e+1),f},d.shiftedBy=function(e){return S(e,-ye,ye),this.times("1e"+e)},d.squareRoot=d.sqrt=function(){var e,t,r,f,i,o=this,l=o.c,n=o.s,s=o.e,c=N+4,a=new g("0.5");if(n!==1||!l||!l[0])return new g(!n||n<0&&(!l||l[0])?NaN:l?o:1/0);if(n=Math.sqrt(+Q(o)),n==0||n==1/0?(t=z(l),(t.length+s)%2==0&&(t+="0"),n=Math.sqrt(+t),s=$((s+1)/2)-(s<0||s%2),n==1/0?t="5e"+s:(t=n.toExponential(),t=t.slice(0,t.indexOf("e")+1)+s),r=new g(t)):r=new g(n+""),r.c[0]){for(s=r.e,n=s+c,n<3&&(n=0);;)if(i=r,r=a.times(i.plus(p(o,i,c,1))),z(i.c).slice(0,n)===(t=z(r.c)).slice(0,n))if(r.e<s&&--n,t=t.slice(n-3,n+1),t=="9999"||!f&&t=="4999"){if(!f&&(F(i,i.e+N+2,0),i.times(i).eq(o))){r=i;break}c+=4,n+=4,f=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(F(r,r.e+N+2,1),e=!r.times(r).eq(o));break}}return F(r,r.e+N+1,O,e)},d.toExponential=function(e,t){return e!=null&&(S(e,0,D),e++),ie(this,e,t,1)},d.toFixed=function(e,t){return e!=null&&(S(e,0,D),e=e+this.e+1),ie(this,e,t)},d.toFormat=function(e,t,r){var f,i=this;if(r==null)e!=null&&t&&typeof t=="object"?(r=t,t=null):e&&typeof e=="object"?(r=e,e=t=null):r=j;else if(typeof r!="object")throw Error(v+"Argument not an object: "+r);if(f=i.toFixed(e,t),i.c){var o,l=f.split("."),n=+r.groupSize,s=+r.secondaryGroupSize,c=r.groupSeparator||"",a=l[0],h=l[1],m=i.s<0,w=m?a.slice(1):a,A=w.length;if(s&&(o=n,n=s,s=o,A-=o),n>0&&A>0){for(o=A%n||n,a=w.substr(0,o);o<A;o+=n)a+=c+w.substr(o,n);s>0&&(a+=c+w.slice(o)),m&&(a="-"+a)}f=h?a+(r.decimalSeparator||"")+((s=+r.fractionGroupSize)?h.replace(new RegExp("\\d{"+s+"}\\B","g"),"$&"+(r.fractionGroupSeparator||"")):h):a}return(r.prefix||"")+f+(r.suffix||"")},d.toFraction=function(e){var t,r,f,i,o,l,n,s,c,a,h,m,w=this,A=w.c;if(e!=null&&(n=new g(e),!n.isInteger()&&(n.c||n.s!==1)||n.lt(I)))throw Error(v+"Argument "+(n.isInteger()?"out of range: ":"not an integer: ")+Q(n));if(!A)return new g(w);for(t=new g(I),c=r=new g(I),f=s=new g(I),m=z(A),o=t.e=m.length-w.e-1,t.c[0]=Ee[(l=o%y)<0?y+l:l],e=!e||n.comparedTo(t)>0?o>0?t:c:n,l=X,X=1/0,n=new g(m),s.c[0]=0;a=p(n,t,0,1),i=r.plus(a.times(f)),i.comparedTo(e)!=1;)r=f,f=i,c=s.plus(a.times(i=c)),s=i,t=n.minus(a.times(i=t)),n=i;return i=p(e.minus(r),f,0,1),s=s.plus(i.times(c)),r=r.plus(i.times(f)),s.s=c.s=w.s,o=o*2,h=p(c,f,o,O).minus(w).abs().comparedTo(p(s,r,o,O).minus(w).abs())<1?[c,f]:[s,r],X=l,h},d.toNumber=function(){return+Q(this)},d.toPrecision=function(e,t){return e!=null&&S(e,1,D),ie(this,e,t,2)},d.toString=function(e){var t,r=this,f=r.s,i=r.e;return i===null?f?(t="Infinity",f<0&&(t="-"+t)):t="NaN":(e==null?t=i<=L||i>=P?ue(z(r.c),i):K(z(r.c),i,"0"):e===10&&ne?(r=F(new g(r),N+i+1,O),t=K(z(r.c),r.e,"0")):(S(e,2,b.length,"Base"),t=x(K(z(r.c),i,"0"),10,e,f,!0)),f<0&&r.c[0]&&(t="-"+t)),t},d.valueOf=d.toJSON=function(){return Q(this)},d._isBigNumber=!0,d[Symbol.toStringTag]="BigNumber",d[Symbol.for("nodejs.util.inspect.custom")]=d.valueOf,u!=null&&g.set(u),g}function $(u){var p=u|0;return u>0||u===p?p:p-1}function z(u){for(var p,x,E=1,d=u.length,I=u[0]+"";E<d;){for(p=u[E++]+"",x=y-p.length;x--;p="0"+p);I+=p}for(d=I.length;I.charCodeAt(--d)===48;);return I.slice(0,d+1||1)}function re(u,p){var x,E,d=u.c,I=p.c,N=u.s,O=p.s,L=u.e,P=p.e;if(!N||!O)return null;if(x=d&&!d[0],E=I&&!I[0],x||E)return x?E?0:-O:N;if(N!=O)return N;if(x=N<0,E=L==P,!d||!I)return E?0:!d^x?1:-1;if(!E)return L>P^x?1:-1;for(O=(L=d.length)<(P=I.length)?L:P,N=0;N<O;N++)if(d[N]!=I[N])return d[N]>I[N]^x?1:-1;return L==P?0:L>P^x?1:-1}function S(u,p,x,E){if(u<p||u>x||u!==H(u))throw Error(v+(E||"Argument")+(typeof u=="number"?u<p||u>x?" out of range: ":" not an integer: ":" not a primitive number: ")+String(u))}function le(u){var p=u.c.length-1;return $(u.e/y)==p&&u.c[p]%2!=0}function ue(u,p){return(u.length>1?u.charAt(0)+"."+u.slice(1):u)+(p<0?"e":"e+")+p}function K(u,p,x){var E,d;if(p<0){for(d=x+".";++p;d+=x);u=d+u}else if(E=u.length,++p>E){for(d=x,p-=E;--p;d+=x);u+=d}else p<E&&(u=u.slice(0,p)+"."+u.slice(p));return u}var Be=Te(),Oe=Be;var he="524C555344000000000000000000000000000000",se={required:"PAYMENT-REQUIRED",signature:"PAYMENT-SIGNATURE",response:"PAYMENT-RESPONSE"};function Z(u){return typeof u=="object"&&u!==null&&!Array.isArray(u)}function U(u,p=!1){if(typeof u!="string"||u.length>100||!(p?/^\d+$/:/^\d+(?:\.\d+)?(?:[eE][+-]?\d{1,2})?$/).test(u))throw new Error("Amount must be a positive decimal string.");let x=new Oe(u);if(!x.isFinite()||x.lte(0)||x.gt("100000000000")||(p?!x.isInteger():x.precision()>16))throw new Error("Amount is outside the supported XRPL range.");return x}function Ce(u,p){return U(u).eq(U(p))}function Me(u){let p=U(u).times(1e6);if(!p.isInteger())throw new Error("XRP amounts must be whole drops.");return p.toFixed(0)}function ae(u){if(!Z(u)||u.scheme!=="exact"||!["xrpl:0","xrpl:1"].includes(u.network)||!["XRP",he].includes(u.asset)||typeof u.payTo!="string"||!Number.isInteger(u.maxTimeoutSeconds)||u.maxTimeoutSeconds<10||u.maxTimeoutSeconds>600||!Z(u.extra)||u.extra.areFeesSponsored!==!1||u.extra.assetTransferMethod!==void 0&&u.extra.assetTransferMethod!=="sequence"||u.extra.invoiceId!==void 0&&(typeof u.extra.invoiceId!="string"||u.extra.invoiceId.length<1||u.extra.invoiceId.length>1024)||u.asset!=="XRP"&&typeof u.extra.issuer!="string"||u.asset==="XRP"&&u.extra.issuer!==void 0||u.extra.destinationTag!==void 0&&(!Number.isInteger(u.extra.destinationTag)||u.extra.destinationTag<0||u.extra.destinationTag>4294967295))throw new Error("Unsupported or invalid XRPL payment requirements.");U(u.amount,u.asset==="XRP")}function Re(u){return ae(u),JSON.stringify([u.scheme,u.network,u.asset,u.amount,u.payTo,u.maxTimeoutSeconds,u.extra.areFeesSponsored,u.extra.assetTransferMethod??"sequence",u.extra.invoiceId??null,u.extra.issuer??null,u.extra.destinationTag??null])}function Ue(u,p){if(ae(p),!Z(u)||u.x402Version!==2||!Z(u.payload)||typeof u.payload.signedTxBlob!="string"||!/^[A-Fa-f0-9]+$/.test(u.payload.signedTxBlob)||u.payload.signedTxBlob.length%2!==0||u.payload.signedTxBlob.length>16384||Re(u.accepted)!==Re(p))throw new Error("Payment payload does not match the required terms.")}function Ae(u){let p=new TextEncoder().encode(JSON.stringify(u)),x="";for(let E of p)x+=String.fromCharCode(E);return btoa(x)}function pe(u){if(u.length>32768||!/^[A-Za-z0-9+/]+={0,2}$/.test(u))throw new Error("Invalid payment header.");let p=Uint8Array.from(atob(u),x=>x.charCodeAt(0));return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(p))}async function ve(u){let p=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return Array.from(new Uint8Array(p),x=>x.toString(16).padStart(2,"0")).join("").toUpperCase()}var Pe=class{options;totalAuthorized=U("1").minus(1);queue=Promise.resolve();unresolvedPayment=!1;pendingReceipt;constructor(p){if(!p?.wallet?.sign||!p.ledgerClient?.autofill||!p.ledgerClient.getLedgerIndex||!["xrpl:0","xrpl:1"].includes(p.network)||!["XRP","RLUSD"].includes(p.currency)||p.currency==="RLUSD"&&!p.issuer)throw new Error("Configure a signing wallet, connected ledger client, network, and currency.");U(p.maxAmount),U(p.maxTotalAmount),U(p.maxFeeDrops??"1000",!0),this.options=p}get authorizedAmount(){return this.totalAuthorized.toFixed()}fetch(p,x,E){let d=this.queue.then(()=>this.fetchOnce(p,x,E));return this.queue=d.catch(()=>{}),d}reconcileReceipt(p){return!this.pendingReceipt||!Z(p)||p.success!==!0||p.network!==this.pendingReceipt.network||p.transaction?.toUpperCase()!==this.pendingReceipt.transaction?!1:(this.unresolvedPayment=!1,this.pendingReceipt=void 0,!0)}selectRequirement(p,x){if(!Z(p)||p.x402Version!==2||!Z(p.resource)||p.resource.url!==x||!Array.isArray(p.accepts))throw new Error("Invalid x402 v2 resource challenge.");for(let E of p.accepts){try{ae(E)}catch{continue}if(E.network===this.options.network&&E.asset===(this.options.currency==="XRP"?"XRP":he)&&(E.asset==="XRP"||E.extra.issuer===this.options.issuer))return E}throw new Error("No payment option matches the configured network and asset.")}async fetchOnce(p,x,E){if(this.unresolvedPayment)throw new Error("A previously authorized payment has an unresolved outcome. Reconcile it before authorizing another payment.");let d=new Request(p,x);if(d.headers.has(se.signature))throw new Error("The agent SDK manages its own payment signature header.");let I=this.options.fetch??globalThis.fetch,N=await I(d.clone());if(N.status!==402)return N;let O=N.headers.get(se.required);if(!O)throw new Error("402 response missing PAYMENT-REQUIRED header.");let L=pe(O),P=this.selectRequirement(L,d.url);if(this.options.allowedRecipients&&!this.options.allowedRecipients.includes(P.payTo))throw new Error("Payment recipient is not allowed.");let V=U(P.amount).div(P.asset==="XRP"?1e6:1);if(V.gt(U(this.options.maxAmount))||this.totalAuthorized.plus(V).gt(U(this.options.maxTotalAmount)))throw new Error("Payment exceeds the agent spending limits.");let X=await this.options.ledgerClient.getLedgerIndex(),Y=P.asset==="XRP"?P.amount:{currency:P.asset,issuer:P.extra.issuer,value:P.amount},te={TransactionType:"Payment",Account:this.options.wallet.address??this.options.wallet.classicAddress,Destination:P.payTo,Amount:Y,...P.extra.invoiceId!==void 0?{InvoiceID:await ve(P.extra.invoiceId)}:{},LastLedgerSequence:X+Math.ceil(P.maxTimeoutSeconds/5),...P.extra.destinationTag!==void 0?{DestinationTag:P.extra.destinationTag}:{},...P.asset!=="XRP"?{SendMax:Y}:{}},C=await this.options.ledgerClient.autofill(te);if(U(C.Fee,!0).gt(U(this.options.maxFeeDrops??"1000",!0)))throw new Error("Network fee exceeds the agent limit.");if(C.TicketSequence!==void 0||C.NetworkID!==void 0||!Number.isInteger(C.Sequence)||C.Sequence<1)throw new Error("Ledger client returned an unsupported account sequence or network.");let j=await this.options.wallet.sign(C);if(!j?.tx_blob||!/^[A-Fa-f0-9]{64}$/.test(j.hash))throw new Error("Wallet did not return a signed XRPL transaction.");this.totalAuthorized=this.totalAuthorized.plus(V),this.unresolvedPayment=!0;let b={x402Version:2,resource:L.resource,accepted:P,payload:{signedTxBlob:j.tx_blob}};this.pendingReceipt={transaction:j.hash.toUpperCase(),network:P.network},E&&await E(b);let ne=d.clone();ne.headers.set(se.signature,Ae(b));let g=await I(new Request(ne,{redirect:"error"})),ie=g.headers.get(se.response);if(ie){let fe=pe(ie);this.reconcileReceipt(fe)}return g}};return De(Xe);})();
|
|
2
|
+
globalThis.X402Client = XRPayX402.X402Client;
|