-
Notifications
You must be signed in to change notification settings - Fork 18
feat: add support for X402 #320
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bumi
wants to merge
16
commits into
master
Choose a base branch
from
x402
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
c0a65cd
feat: add support for X402
bumi 42be548
chore: cleanup
bumi 3943ba9
chore: default to no storage
bumi 4814875
feat: add fetch402 function
bumi ed3bbc3
Update README.md
bumi 248dcc7
chore: cleanup and require NWC compatible wallet interface
bumi b3ee2af
test: x402/l402 generated tests
bumi ee426e6
docs: update readme
bumi 401d27f
docs: readme
bumi fe45a87
feat: use proper Header object to better handle http headers
bumi bf14464
fix: ai fixing the tests on CI
bumi e31ce7f
feat: expose millisats amount in Invoice
bumi 1dd777e
feat: new X402 lightning spec
bumi 35e9c99
test: adjust tests
bumi ff358fa
fix: updated paymentMethod, remove preimage
reneaaron ca4bd17
fix: split x402 / l402 + shared utils
reneaaron File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { fetch402 } from "@getalby/lightning-tools/402"; | ||
| import { NWCClient } from "@getalby/sdk"; | ||
|
|
||
| // fetch402 works with both L402 and X402 endpoints — | ||
| // it detects the protocol from the server's response headers automatically. | ||
| const url = process.env.URL || "https://x402.albylabs.com/demo/quote"; | ||
|
|
||
| const nostrWalletConnectUrl = process.env.NWC_URL; | ||
|
|
||
| if (!nostrWalletConnectUrl) { | ||
| throw new Error("Please set a NWC_URL env variable"); | ||
| } | ||
|
|
||
| const nwc = new NWCClient({ | ||
| nostrWalletConnectUrl, | ||
| }); | ||
|
|
||
| fetch402(url, {}, { wallet: nwc }) | ||
| .then((response) => response.json()) | ||
| .then((data) => { | ||
| console.info(data); | ||
| nwc.close(); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import { fetchWithX402 } from "@getalby/lightning-tools/l402"; | ||
| import { NostrWebLNProvider } from "@getalby/sdk"; | ||
| import "websocket-polyfill"; | ||
|
|
||
| const url = "https://x402.albylabs.com/demo/quote"; | ||
|
|
||
| const nostrWalletConnectUrl = process.env.NWC_URL; | ||
|
|
||
| if (!nostrWalletConnectUrl) { | ||
| throw new Error("Please set a NWC_URL env variable"); | ||
| } | ||
|
|
||
| const nwc = new NostrWebLNProvider({ | ||
| nostrWalletConnectUrl, | ||
| }); | ||
| await nwc.enable(); | ||
| nwc.on("payInvoice", (response) => { | ||
| console.info(`payment response:`, response); | ||
| }); | ||
|
|
||
| fetchWithX402(url, {}, { wallet: nwc }) | ||
| .then((response) => response.json()) | ||
| .then((data) => { | ||
| console.info(data); | ||
| nwc.close(); | ||
| }); | ||
bumi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,8 +1,9 @@ | ||
| /** @type {import('ts-jest').JestConfigWithTsJest} */ | ||
| module.exports = { | ||
| preset: 'ts-jest', | ||
| testEnvironment: 'node', | ||
| setupFiles: [ | ||
| "./setupJest.ts" | ||
| ] | ||
| }; | ||
| import type { Config } from "jest"; | ||
|
|
||
| const config: Config = { | ||
| preset: "ts-jest", | ||
| testEnvironment: "node", | ||
| setupFiles: ["./setupJest.ts"], | ||
| }; | ||
|
|
||
| export default config; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| import { KVStorage, NoStorage, Wallet } from "./utils"; | ||
| import { parseL402 } from "./l402/utils"; | ||
| import { buildX402PaymentSignature, X402Requirements } from "./x402/utils"; | ||
| import { HEADER_KEY } from "./l402/l402"; | ||
|
|
||
| const noStorage = new NoStorage(); | ||
|
|
||
| export const fetch402 = async ( | ||
| url: string, | ||
| fetchArgs: RequestInit, | ||
| options: { | ||
| wallet: Wallet; | ||
| store?: KVStorage; | ||
| }, | ||
| ) => { | ||
| const wallet = options.wallet; | ||
| const store = options.store || noStorage; | ||
| if (!fetchArgs) { | ||
| fetchArgs = {}; | ||
| } | ||
| fetchArgs.cache = "no-store"; | ||
| fetchArgs.mode = "cors"; | ||
| const headers = new Headers(fetchArgs.headers ?? undefined); | ||
| fetchArgs.headers = headers; | ||
|
|
||
| // Check cache — detect protocol from stored data structure | ||
| const cachedRaw = store.getItem(url); | ||
| if (cachedRaw) { | ||
| const cached = JSON.parse(cachedRaw); | ||
| if (cached?.token && cached?.preimage) { | ||
bumi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| // L402 cached | ||
| headers.set( | ||
| "Authorization", | ||
| `${HEADER_KEY} ${cached.token}:${cached.preimage}`, | ||
| ); | ||
| return await fetch(url, fetchArgs); | ||
| } | ||
| if ( | ||
| cached?.scheme && | ||
| cached?.network && | ||
| cached?.invoice && | ||
| cached?.requirements | ||
| ) { | ||
| // X402 cached | ||
| headers.set( | ||
| "payment-signature", | ||
| buildX402PaymentSignature( | ||
| cached.scheme, | ||
| cached.network, | ||
| cached.invoice, | ||
| cached.requirements, | ||
| ), | ||
| ); | ||
| return await fetch(url, fetchArgs); | ||
| } | ||
| } | ||
|
|
||
| // Initial request — advertise L402 support | ||
| headers.set("Accept-Authenticate", HEADER_KEY); | ||
| const initResp = await fetch(url, fetchArgs); | ||
|
|
||
| const l402Header = initResp.headers.get("www-authenticate"); | ||
| if (l402Header) { | ||
| const details = parseL402(l402Header); | ||
| const token = details.token || details.macaroon; | ||
| const invoice = details.invoice; | ||
|
|
||
| const invResp = await wallet.payInvoice!({ invoice }); | ||
|
|
||
| store.setItem(url, JSON.stringify({ token, preimage: invResp.preimage })); | ||
|
|
||
| headers.set("Authorization", `${HEADER_KEY} ${token}:${invResp.preimage}`); | ||
|
|
||
| return await fetch(url, fetchArgs); | ||
| } | ||
|
|
||
| const x402Header = initResp.headers.get("PAYMENT-REQUIRED"); | ||
| if (x402Header) { | ||
| let parsed: { accepts?: unknown[] }; | ||
| try { | ||
| parsed = JSON.parse(decodeURIComponent(escape(atob(x402Header)))); | ||
| } catch (_) { | ||
| throw new Error( | ||
| "x402: invalid PAYMENT-REQUIRED header (not valid base64-encoded JSON)", | ||
| ); | ||
| } | ||
|
|
||
| if (!Array.isArray(parsed.accepts) || parsed.accepts.length === 0) { | ||
| throw new Error( | ||
| "x402: PAYMENT-REQUIRED header contains no payment options", | ||
| ); | ||
| } | ||
|
|
||
| const requirements = (parsed.accepts as X402Requirements[]).find((e) => { | ||
| return e.extra?.paymentMethod === "lightning"; | ||
| }); | ||
| if (!requirements) { | ||
| throw new Error( | ||
| "x402: unsupported x402 network, only lightning networks are supported", | ||
| ); | ||
| } | ||
| if (!requirements.extra?.invoice) { | ||
| throw new Error("x402: payment requirements missing lightning invoice"); | ||
| } | ||
|
|
||
| const invoice = requirements.extra.invoice; | ||
| await wallet.payInvoice!({ invoice }); | ||
|
|
||
| store.setItem( | ||
| url, | ||
| JSON.stringify({ | ||
| scheme: requirements.scheme, | ||
| network: requirements.network, | ||
| invoice, | ||
| requirements, | ||
| }), | ||
| ); | ||
|
|
||
| headers.set( | ||
| "payment-signature", | ||
| buildX402PaymentSignature( | ||
| requirements.scheme, | ||
| requirements.network, | ||
| invoice, | ||
| requirements, | ||
| ), | ||
| ); | ||
| return await fetch(url, fetchArgs); | ||
| } | ||
|
|
||
| return initResp; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| export * from "./fetch402"; | ||
| export * from "./utils"; |
File renamed without changes.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.