better-auth-solana-payments 0.4.0 → 0.5.0

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.
@@ -0,0 +1,91 @@
1
+ [English](README.md) · [Español](README.es-ES.md) · [Français](README.fr-FR.md)
2
+
3
+ # Better Auth Solana Payments
4
+
5
+ Acepta pagos únicos con Solana Pay para usuarios u organizaciones de Better Auth. El servidor verifica las transferencias mediante RPC de solo lectura.
6
+
7
+ ## Instalación
8
+
9
+ ```sh
10
+ pnpm add better-auth better-auth-solana-payments solana-payments
11
+ ```
12
+
13
+ Requiere Node.js 22+, Better Auth `>=1.4.22 <2` y `solana-payments` `^1.1.0`.
14
+
15
+ ## Configurar Better Auth
16
+
17
+ Define `SOLANA_RPC_URL` y `SOLANA_RECIPIENT` en el servidor. El ejemplo usa el mint de USDT de mainnet. Elige un mint y una URL RPC de la misma red.
18
+
19
+ ```ts
20
+ import { betterAuth } from "better-auth";
21
+ import { solanaPayments } from "better-auth-solana-payments";
22
+ import { SOLANA_USDT, createReadOnlySolanaPayments } from "solana-payments";
23
+
24
+ const client = createReadOnlySolanaPayments({
25
+ rpcUrl: process.env.SOLANA_RPC_URL!,
26
+ token: SOLANA_USDT,
27
+ commitment: "confirmed",
28
+ });
29
+
30
+ export const auth = betterAuth({
31
+ plugins: [solanaPayments({ client, recipient: process.env.SOLANA_RECIPIENT! })],
32
+ });
33
+ ```
34
+
35
+ Usa un adaptador persistente, monta el controlador de Better Auth y aplica el esquema del plugin antes de aceptar pagos. Si tu instalación carece de los campos de entrega, sigue la [guía de migración](skills/solana-payment-verification/SKILL.md#existing-databases).
36
+
37
+ ```ts
38
+ import { createAuthClient } from "better-auth/client";
39
+ import { solanaPaymentsClient } from "better-auth-solana-payments/client";
40
+
41
+ export const authClient = createAuthClient({ plugins: [solanaPaymentsClient()] });
42
+ ```
43
+
44
+ ## Cobrar un pago
45
+
46
+ Crea una intención desde una sesión autenticada con una cadena decimal en las unidades de visualización del token.
47
+
48
+ ```ts
49
+ const { data, error } = await authClient.payment.create({ amount: "2.5" });
50
+ if (error || !data?.paymentUrl) {
51
+ throw new Error(error?.message ?? "Could not create Solana payment");
52
+ }
53
+
54
+ const { reference, paymentUrl } = data;
55
+ ```
56
+
57
+ Guarda la referencia con el pedido del servidor. Presenta la URL como enlace de Solana Pay o código QR. Tras el envío desde la cartera, llama a `authClient.payment.verify({ reference })` e incluye la firma si está disponible. Usa `authClient.payment.get({ reference })` para leer el estado almacenado.
58
+
59
+ Comprueba el pago contra el pedido en el servidor y haz que `onPaymentComplete` sea idempotente por referencia. Concede acceso cuando el pago esté `paid` y la entrega `completed`. Para pagos de organización, activa el plugin de organización de Better Auth y configura `organization.enabled` en el plugin de Solana e incluye el mismo `organizationId` en cada llamada. [Configuración](skills/better-auth-solana-payments-setup/SKILL.md) · [Verificación y entrega](skills/solana-payment-verification/SKILL.md)
60
+
61
+ ## Proyectos independientes
62
+
63
+ Crea un proyecto con npm. TanStack Start es la opción predeterminada.
64
+
65
+ ```sh
66
+ npm create better-auth-solana-payments@latest my-app
67
+ npm create better-auth-solana-payments@latest my-next-app -- --template nextjs
68
+ npm create better-auth-solana-payments@latest my-worker -- --template hono
69
+ ```
70
+
71
+ Configura el entorno según el README generado y ejecuta `pnpm install --frozen-lockfile` y `pnpm dev`.
72
+
73
+ Descarga el proyecto independiente de TanStack en la próxima versión. El archivo incluye el lockfile y una plantilla de entorno. Extráelo, configura el entorno y ejecuta `pnpm install --frozen-lockfile` y `pnpm dev`. [GitHub Releases](https://github.com/alexasomba/better-auth-solana-payments/releases)
74
+
75
+ Desde el repositorio, exporta la demo con el paquete publicado o con un tarball local generado mediante `vp pack` y `pnpm pack`.
76
+
77
+ ```sh
78
+ pnpm starter:export tanstack /tmp/solana-starter
79
+ pnpm starter:export tanstack /tmp/solana-local --tarball /path/to/better-auth-solana-payments.tgz
80
+ ```
81
+
82
+ ## Demo y habilidades para agentes
83
+
84
+ [TanStack Start](examples/tanstack/README.md) y [Next.js](examples/nextjs/README.md) muestran inicio de sesión, pago con cartera y verificación. [Hono](examples/hono/README.md) ofrece la API de pagos en un Worker.
85
+
86
+ El paquete npm incluye [habilidades para agentes](skills). Con pnpm 12.11 o posterior, ejecuta `pnpm approve` tras instalarlo y aprueba sus habilidades cuando se te solicite. TanStack Intent puede localizar y cargar los mismos archivos.
87
+
88
+ ```sh
89
+ pnpm dlx @tanstack/intent list
90
+ pnpm dlx @tanstack/intent load better-auth-solana-payments#better-auth-solana-payments-setup
91
+ ```
@@ -0,0 +1,91 @@
1
+ [English](README.md) · [Español](README.es-ES.md) · [Français](README.fr-FR.md)
2
+
3
+ # Better Auth Solana Payments
4
+
5
+ Acceptez les paiements ponctuels via Solana Pay pour les utilisateurs ou les organisations Better Auth. Le serveur vérifie les transferts par RPC en lecture seule.
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ pnpm add better-auth better-auth-solana-payments solana-payments
11
+ ```
12
+
13
+ Utilisez Node.js 22+, Better Auth `>=1.4.22 <2` et `solana-payments` `^1.1.0`.
14
+
15
+ ## Configurer Better Auth
16
+
17
+ Définissez `SOLANA_RPC_URL` et `SOLANA_RECIPIENT` côté serveur. Cet exemple utilise le mint USDT du réseau principal. Choisissez un mint et une URL RPC sur le même réseau.
18
+
19
+ ```ts
20
+ import { betterAuth } from "better-auth";
21
+ import { solanaPayments } from "better-auth-solana-payments";
22
+ import { SOLANA_USDT, createReadOnlySolanaPayments } from "solana-payments";
23
+
24
+ const client = createReadOnlySolanaPayments({
25
+ rpcUrl: process.env.SOLANA_RPC_URL!,
26
+ token: SOLANA_USDT,
27
+ commitment: "confirmed",
28
+ });
29
+
30
+ export const auth = betterAuth({
31
+ plugins: [solanaPayments({ client, recipient: process.env.SOLANA_RECIPIENT! })],
32
+ });
33
+ ```
34
+
35
+ Utilisez un adaptateur persistant, montez le gestionnaire Better Auth et appliquez le schéma du plugin avant d’accepter des paiements. Si les champs d’exécution manquent dans votre installation, suivez le [guide de migration](skills/solana-payment-verification/SKILL.md#existing-databases).
36
+
37
+ ```ts
38
+ import { createAuthClient } from "better-auth/client";
39
+ import { solanaPaymentsClient } from "better-auth-solana-payments/client";
40
+
41
+ export const authClient = createAuthClient({ plugins: [solanaPaymentsClient()] });
42
+ ```
43
+
44
+ ## Encaisser un paiement
45
+
46
+ Créez une intention dans une session authentifiée. Transmettez le montant décimal sous forme de chaîne dans l’unité d’affichage du jeton.
47
+
48
+ ```ts
49
+ const { data, error } = await authClient.payment.create({ amount: "2.5" });
50
+ if (error || !data?.paymentUrl) {
51
+ throw new Error(error?.message ?? "Could not create Solana payment");
52
+ }
53
+
54
+ const { reference, paymentUrl } = data;
55
+ ```
56
+
57
+ Conservez la référence avec la commande côté serveur. Présentez l’URL sous forme de lien Solana Pay ou de code QR. Après l’envoi depuis le portefeuille, appelez `authClient.payment.verify({ reference })` et joignez la signature si elle est disponible. Utilisez `authClient.payment.get({ reference })` pour lire l’état enregistré.
58
+
59
+ Rapprochez le paiement de la commande côté serveur et rendez `onPaymentComplete` idempotent par référence. Accordez l’accès lorsque le paiement est `paid` et son exécution `completed`. Pour les paiements d’organisation, activez le plugin d’organisation de Better Auth et configurez `organization.enabled` dans le plugin Solana et fournissez le même `organizationId` à chaque appel. [Configuration](skills/better-auth-solana-payments-setup/SKILL.md) · [Vérification et exécution](skills/solana-payment-verification/SKILL.md)
60
+
61
+ ## Starters autonomes
62
+
63
+ Créez un projet avec npm. TanStack Start est le choix par défaut.
64
+
65
+ ```sh
66
+ npm create better-auth-solana-payments@latest my-app
67
+ npm create better-auth-solana-payments@latest my-next-app -- --template nextjs
68
+ npm create better-auth-solana-payments@latest my-worker -- --template hono
69
+ ```
70
+
71
+ Configurez l’environnement selon le README généré, puis exécutez `pnpm install --frozen-lockfile` et `pnpm dev`.
72
+
73
+ Téléchargez le starter TanStack autonome dans la prochaine version. L’archive contient le fichier de verrouillage et un modèle d’environnement. Extrayez-la, configurez l’environnement, puis exécutez `pnpm install --frozen-lockfile` et `pnpm dev`. [GitHub Releases](https://github.com/alexasomba/better-auth-solana-payments/releases)
74
+
75
+ Depuis le dépôt, exportez la démo avec le paquet publié ou une archive locale créée via `vp pack` puis `pnpm pack`.
76
+
77
+ ```sh
78
+ pnpm starter:export tanstack /tmp/solana-starter
79
+ pnpm starter:export tanstack /tmp/solana-local --tarball /path/to/better-auth-solana-payments.tgz
80
+ ```
81
+
82
+ ## Démo et compétences pour agents
83
+
84
+ [TanStack Start](examples/tanstack/README.md) et [Next.js](examples/nextjs/README.md) présentent la connexion, le paiement par portefeuille et la vérification. [Hono](examples/hono/README.md) expose l’API de paiements dans un Worker.
85
+
86
+ Le paquet npm inclut des [compétences pour agents](skills). Avec pnpm 12.11 ou une version ultérieure, exécutez `pnpm approve` après l’installation et approuvez les compétences proposées. TanStack Intent peut répertorier et charger les mêmes fichiers.
87
+
88
+ ```sh
89
+ pnpm dlx @tanstack/intent list
90
+ pnpm dlx @tanstack/intent load better-auth-solana-payments#better-auth-solana-payments-setup
91
+ ```
package/README.md CHANGED
@@ -1,20 +1,22 @@
1
+ [English](README.md) · [Español](README.es-ES.md) · [Français](README.fr-FR.md)
2
+
1
3
  # Better Auth Solana Payments
2
4
 
3
- One-time Solana payment integration for [Better Auth](https://www.better-auth.com).
5
+ Accept one-time Solana Pay payments for users or organizations with Better Auth. The server uses read-only RPC to verify transfers.
4
6
 
5
- ## Installation
7
+ ## Install
6
8
 
7
- ```bash
9
+ ```sh
8
10
  pnpm add better-auth better-auth-solana-payments solana-payments
9
11
  ```
10
12
 
11
- Requires Node.js 22.22.2 or later and solana-payments 1.x.
13
+ Requires Node.js 22+, Better Auth `>=1.4.22 <2`, and `solana-payments` `^1.1.0`.
12
14
 
13
- Existing installations must add the fulfillment fields before upgrading. For the default SQLite table and column names, see `migrations/0.2.0-sqlite.sql`; custom schemas must generate the equivalent Better Auth migration. Back up the database, verify paid-row fulfillment state, then deploy.
15
+ See the [API and compatibility policy](COMPATIBILITY.md).
14
16
 
15
- ## Server setup
17
+ ## Configure Better Auth
16
18
 
17
- Create a read-only Solana Payments SDK client and register the Better Auth plugin.
19
+ Set `SOLANA_RPC_URL` and `SOLANA_RECIPIENT` on the server. This example uses the mainnet USDT mint. Choose a matching mint and RPC endpoint for your cluster.
18
20
 
19
21
  ```ts
20
22
  import { betterAuth } from "better-auth";
@@ -28,170 +30,64 @@ const client = createReadOnlySolanaPayments({
28
30
  });
29
31
 
30
32
  export const auth = betterAuth({
31
- plugins: [
32
- solanaPayments({
33
- client,
34
- recipient: process.env.SOLANA_RECIPIENT!,
35
- }),
36
- ],
33
+ plugins: [solanaPayments({ client, recipient: process.env.SOLANA_RECIPIENT! })],
37
34
  });
38
35
  ```
39
36
 
40
- ## Client setup
37
+ Use a persistent Better Auth database adapter and mount your auth handler. Generate and apply the plugin schema before accepting payments. Existing installations that lack fulfillment fields should follow the [migration instructions](skills/solana-payment-verification/SKILL.md#existing-databases).
41
38
 
42
39
  ```ts
43
40
  import { createAuthClient } from "better-auth/client";
44
41
  import { solanaPaymentsClient } from "better-auth-solana-payments/client";
45
42
 
46
- export const authClient = createAuthClient({
47
- plugins: [solanaPaymentsClient()],
48
- });
43
+ export const authClient = createAuthClient({ plugins: [solanaPaymentsClient()] });
49
44
  ```
50
45
 
51
- ## One-time payment flow
52
-
53
- ```ts
54
- const created = await authClient.payment.create({
55
- // A decimal string in the configured token's display units; never use a JavaScript number.
56
- amount: "2.5",
57
- metadata: { orderId: "order_123" },
58
- });
46
+ ## Take a payment
59
47
 
60
- if (created.data?.paymentUrl) {
61
- // Present this Solana Pay URL as a link or QR code for the signed-in customer.
62
- window.location.assign(created.data.paymentUrl);
63
- }
48
+ Create an intent from an authenticated session using a decimal string in token display units.
64
49
 
65
- const verified = await authClient.payment.verify({
66
- reference: created.data!.reference,
67
- });
68
-
69
- if (verified.data?.status === "paid" && verified.data.fulfillmentStatus === "completed") {
70
- // Grant the entitlement only after server-side verification and fulfillment complete.
50
+ ```ts
51
+ const { data, error } = await authClient.payment.create({ amount: "2.5" });
52
+ if (error || !data?.paymentUrl) {
53
+ throw new Error(error?.message ?? "Could not create Solana payment");
71
54
  }
72
55
 
73
- const payment = await authClient.payment.get({
74
- reference: created.data!.reference,
75
- });
76
- ```
77
-
78
- `payment.create` persists a pending payment intent and returns its reference and Solana Pay URL.
79
- After the customer signs the transaction, call `payment.verify` with that reference. The server
80
- uses its configured RPC client to verify the matching token transfer before marking the payment
81
- paid. `payment.get` reads the current status without attempting verification.
82
-
83
- Amounts are decimal strings in the configured token's display units (for example, `"2.5"` is
84
- 2.5 USDT with the default six-decimal USDT token). Do not pass JavaScript numbers, which can lose
85
- precision for token amounts.
86
-
87
- If the wallet already returned a transaction signature, send it as the optional `signature` field
88
- to `payment.verify`. The SDK checks that candidate before scanning recent transactions, while still
89
- verifying the configured mint, recipient, amount, cluster and confirmation commitment. The plugin
90
- inherits the token program configured on the server's SDK client. Basic Token-2022 transfers are
91
- supported; transfer-fee and transfer-hook mints need extension-aware verification and are not
92
- accepted as ordinary transfers. See Solana's [payment verification guidance](https://solana.com/docs/payments/accept-payments/verification-tools)
93
- and [Token Extensions documentation](https://solana.com/docs/tokens/extensions) when configuring a mint.
94
-
95
- The browser may supply the amount, optional metadata, reference, optional transaction signature,
96
- and optional organization ID. The server controls the recipient and token configuration, so clients
97
- cannot redirect funds or choose another mint. The integration uses a read-only RPC client: it stores
98
- no private keys and never signs or sends a transaction on behalf of a customer.
99
-
100
- This package supports one-time payments only. It does not create recurring subscriptions or
101
- perform recurring charges.
102
-
103
- ## TanStack Start example
104
-
105
- The repository includes a runnable TanStack Start example at
106
- [`examples/tanstack`](./examples/tanstack). It demonstrates email/password auth, server-created
107
- Solana Pay requests, wallet checkout, and server-side verification against devnet RPC.
108
-
109
- ```bash
110
- cd examples/tanstack
111
- cp .env.example .env
112
- # Set SOLANA_MINT and SOLANA_RECIPIENT to your devnet SPL token and recipient.
113
- pnpm install
114
- pnpm dev
56
+ const { reference, paymentUrl } = data;
115
57
  ```
116
58
 
117
- The example uses an in-memory adapter and is intended for local development only. It does not
118
- store private keys or submit transactions. See its README for the repeatable RPC and on-chain
119
- smoke test (`pnpm test:devnet`) and the full wallet verification flow.
120
-
121
- For devnet, configure a devnet SPL-token mint; the built-in `SOLANA_USDT` preset is the mainnet
122
- USDT mint and must not be used for devnet testing. In production, use a persistent Better Auth
123
- adapter, a generated `BETTER_AUTH_SECRET`, and a dedicated RPC provider.
124
-
125
- ### Fulfillment migration and retries
126
-
127
- Generate/apply your Better Auth schema migration before upgrading. Add `fulfillmentStatus` (default `pending`), nullable `fulfillmentToken`, and nullable `fulfillmentClaimedAt` to `solanaPayment`. Backfill previously paid rows to `completed` before accepting requests, so historical payments are not fulfilled again.
128
-
129
- Payment settlement and fulfillment are separate: verification persists `paid`, then claims a database lease before invoking `onPaymentComplete`. Failed callbacks return an error and leave fulfillment pending; retry verification to recover, including after a restart. A crashed worker's claim becomes recoverable after five minutes. Callbacks must be idempotent by payment reference, since a crash after an external side effect can cause a retry. Responses expose `fulfillmentStatus`; grant access only when it is `completed`.
130
-
131
- ## Settlement and operational edge cases
59
+ Keep the reference with your server-owned order. Present the payment URL as a Solana Pay link or QR code. After the customer submits the transaction, call `authClient.payment.verify({ reference })` and include the wallet's signature if available. Use `authClient.payment.get({ reference })` to read the stored status.
132
60
 
133
- ### Confirmation depth
61
+ Match the payment to the order on the server and make `onPaymentComplete` idempotent by reference. Grant access after the payment is `paid` and fulfillment is `completed`. For organization payments, enable Better Auth's organization plugin and set `organization.enabled` in the Solana plugin and include the same `organizationId` on each payment call. See the [setup](skills/better-auth-solana-payments-setup/SKILL.md) and [verification](skills/solana-payment-verification/SKILL.md) guides.
134
62
 
135
- The SDK verifier requires at least `confirmed`, even if its client is configured with
136
- `processed`. Configure `commitment: "finalized"` when your application needs the strongest
137
- settlement state before fulfillment; a merely confirmed transaction then remains unaccepted.
138
- This is a commitment policy, not a configurable number of confirmations. Failed execution
139
- is rejected regardless of commitment. See [Solana's commitment definitions](https://solana.com/docs/rpc#configuring-state-commitment).
63
+ ## Standalone starters
140
64
 
141
- Show an awaiting-confirmation state and retry server verification with bounded backoff for
142
- an unsettled transfer or RPC failure. `PAYMENT_MISMATCH` alone does not distinguish an
143
- unconfirmed transfer, absent transfer, wrong token/network, or a provider error. A browser
144
- wallet success notification is not settlement proof. Grant an entitlement only when the
145
- response has both `status === "paid"` and `fulfillmentStatus === "completed"`.
65
+ Scaffold a project with npm. TanStack Start is the default.
146
66
 
147
- Choose the commitment before accepting payments and keep it consistent: an already-paid
148
- intent retries fulfillment without re-verifying the chain, so changing the client to
149
- `finalized` does not upgrade previously recorded confirmed payments automatically.
150
-
151
- ### Duplicate verification and callbacks
152
-
153
- Repeated browser verification calls share the stored payment. A conditional database claim
154
- allows one active fulfillment callback; completed fulfillment is not called again. Callback
155
- failure releases the claim for retry, and a crashed claim can be recovered after five minutes.
156
- This does not guarantee exactly-once external side effects: a crash after issuing an email,
157
- granting access, or updating another service can happen before completion is persisted.
67
+ ```sh
68
+ npm create better-auth-solana-payments@latest my-app
69
+ npm create better-auth-solana-payments@latest my-next-app -- --template nextjs
70
+ npm create better-auth-solana-payments@latest my-worker -- --template hono
71
+ ```
158
72
 
159
- Make `onPaymentComplete` idempotent using the payment reference as a durable business key.
160
- Use a unique entitlement/fulfillment record and a transaction or outbox where possible;
161
- pass the same reference as an external service's idempotency key. Retry verification after
162
- a transient failure, including after a restart. The fulfillment migration and a persistent
163
- adapter are required; an in-memory adapter cannot coordinate separate workers.
73
+ Set the environment variables from the generated README, then run `pnpm install --frozen-lockfile` and `pnpm dev`.
164
74
 
165
- ### Refunds
75
+ Download the standalone TanStack starter from the next release. The archive includes the lockfile and environment template. Extract it, configure the sample environment file, then run `pnpm install --frozen-lockfile` and `pnpm dev`. [GitHub Releases](https://github.com/alexasomba/better-auth-solana-payments/releases)
166
76
 
167
- This read-only plugin has no refund endpoint and no `refunded` payment status. A refund is a
168
- separate authorized on-chain transfer, not a rollback of the settled transaction. Keep the
169
- original paid record as settlement evidence. An application refund ledger should record the
170
- payment reference, approved amount, token mint, cluster, destination, refund signature and
171
- confirmation state, and reconcile retries idempotently before sending again.
77
+ From a repository checkout, export a starter with the released package or with a local tarball built by `vp pack` followed by `pnpm pack`.
172
78
 
173
- Verify the refund destination through your application's authenticated review flow; do not
174
- trust a browser-supplied address or infer the payer from an arbitrary transaction account.
175
- Use a separate controlled signing service/manual process. Mark a refund complete only after
176
- its chosen confirmation policy succeeds, then apply the application's entitlement policy.
177
- The plugin neither signs refunds nor automatically revokes access.
79
+ ```sh
80
+ pnpm starter:export tanstack /tmp/solana-starter
81
+ pnpm starter:export tanstack /tmp/solana-local --tarball /path/to/better-auth-solana-payments.tgz
82
+ ```
178
83
 
179
- ### Right token, wrong network
84
+ ## Demo and agent skills
180
85
 
181
- Token symbols are labels; the asset is identified by its cluster and mint address. Verification
182
- uses the server's configured RPC endpoint and token, and does not search other networks. A
183
- transfer on another Solana cluster, or USDT sent through another chain, does not settle this
184
- intent. The mainnet `SOLANA_USDT` preset is not a devnet token. See [Solana clusters](https://solana.com/docs/references/clusters).
86
+ The [TanStack Start](examples/tanstack/README.md) and [Next.js](examples/nextjs/README.md) demos walk through sign-in, wallet checkout, and transfer verification. The [Hono example](examples/hono/README.md) exposes the same payment API from a Worker.
185
87
 
186
- Show the required network and mint before payment, check the wallet's network where possible,
187
- and keep the RPC/cluster/mint configuration fixed for outstanding intents. If verification
188
- cannot find a matching transfer, leave access unfulfilled; the intent remains pending until
189
- expiry. Do not switch the production verifier to another network or manually mark the intent
190
- paid to make the transaction appear to match.
88
+ The npm package includes [agent skills](skills). With pnpm 12.11 or later, run `pnpm approve` after installing the package and approve its skills when prompted. TanStack Intent can list and load the same files from your project.
191
89
 
192
- Collect the transaction signature, actual network, mint and recipient for a support case,
193
- and independently verify them on that network. A missing result is not proof that funds were
194
- never sent. Explain that recovery depends on control of the recipient on the actual network;
195
- this plugin cannot bridge, reverse or recover those funds. If a reviewed recovery/refund is
196
- possible, track it separately and ask the customer to create a new intent on the required
197
- network. Never request a wallet seed phrase or private key.
90
+ ```sh
91
+ pnpm dlx @tanstack/intent list
92
+ pnpm dlx @tanstack/intent load better-auth-solana-payments#better-auth-solana-payments-setup
93
+ ```
package/dist/client.d.mts CHANGED
@@ -1,7 +1,6 @@
1
- import { t as solanaPayments } from "./index-DlPQtl6v.mjs";
2
- import { BetterFetch, BetterFetchOption, BetterFetchResponse } from "@better-fetch/fetch";
1
+ import { c as PACKAGE_VERSION, t as solanaPayments } from "./index-BQ-nihZA.mjs";
2
+ import { BetterFetchOption, BetterFetchResponse } from "@better-fetch/fetch";
3
3
  import { BetterAuthClientPlugin } from "better-auth/client";
4
- //#region src/client.d.ts
5
4
  export type FetchResult<T, O extends BetterFetchOption | undefined> = O extends {
6
5
  throw: true;
7
6
  } ? T : BetterFetchResponse<T>;
@@ -49,11 +48,12 @@ declare module "better-auth" {
49
48
  solanaPayments: ReturnType<typeof solanaPaymentsClient>;
50
49
  }
51
50
  }
52
- type SolanaPaymentsClientPluginInstance = Omit<BetterAuthClientPlugin, "id" | "$InferServerPlugin" | "getActions"> & {
51
+ type SolanaPaymentsClientPluginInstance = Omit<BetterAuthClientPlugin, "id" | "version" | "$InferServerPlugin" | "getActions"> & {
53
52
  id: "solanaPayments";
53
+ version: typeof PACKAGE_VERSION;
54
54
  $InferServerPlugin: ReturnType<typeof solanaPayments>;
55
- getActions: ($fetch: BetterFetch, $store: unknown, options: unknown) => SolanaPaymentsClientActions;
55
+ getActions: ($fetch: Parameters<NonNullable<BetterAuthClientPlugin["getActions"]>>[0], $store: unknown, options: unknown) => SolanaPaymentsClientActions;
56
56
  };
57
57
  export declare const solanaPaymentsClient: () => SolanaPaymentsClientPluginInstance;
58
- //#endregion
58
+ export {};
59
59
  //# sourceMappingURL=client.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.mts","names":["solanaPaymentsServer"],"sources":["../src/client.ts"],"mappings":";;;;YAMY,YAAY,GAAG,UAAU,iCAAiC;EAAY;IAC9E,IACA,oBAAoB;iBAEP;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAW;EACX;EACA;EACA,WAAW;EACX;;iBAGe;EACf,SAAS,UAAU,2CACjB;IACE;IACA,WAAW;IACX;KAEF,UAAU,MACP,QAAQ,YAAY,uBAAuB;EAChD,SAAS,UAAU,2CACjB;IAAQ;IAAmB;IAAoB;KAC/C,UAAU,MACP,QAAQ,YAAY,uBAAuB;EAChD,MAAM,UAAU,2CACd;IAAQ;IAAmB;KAC3B,UAAU,MACP,QAAQ,YAAY,uBAAuB;;iBAGjC;EACf,SAAS;;;YAIC;IACR,SAAS;;;;YAKD;IACR,gBAAgB,kBAAkB;;;KAIjC,qCAAqC,KACxC;EAGA;EACA,oBAAoB,kBAAkBA;EACtC,aACE,QAAQ,aACR,iBACA,qBACG;;qBAGM,4BAA2B"}
1
+ {"version":3,"file":"client.d.mts","names":["solanaPaymentsServer"],"sources":["../src/client.ts"],"mappings":";;;YAMY,YAAY,GAAG,UAAU,iCAAiC;EAAY;IAC9E,IACA,oBAAoB;iBAEP;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,WAAW;EACX;EACA;EACA,WAAW;EACX;;iBAGe;EACf,SAAS,UAAU,2CACjB;IACE;IACA,WAAW;IACX;KAEF,UAAU,MACP,QAAQ,YAAY,uBAAuB;EAChD,SAAS,UAAU,2CACjB;IAAQ;IAAmB;IAAoB;KAC/C,UAAU,MACP,QAAQ,YAAY,uBAAuB;EAChD,MAAM,UAAU,2CACd;IAAQ;IAAmB;KAC3B,UAAU,MACP,QAAQ,YAAY,uBAAuB;;iBAGjC;EACf,SAAS;;;YAIC;IACR,SAAS;;;;YAKD;IACR,gBAAgB,kBAAkB;;;KAIjC,qCAAqC,KACxC;EAGA;EACA,gBAAgB;EAChB,oBAAoB,kBAAkBA;EACtC,aACE,QAAQ,WAAW,YAAY,2CAC/B,iBACA,qBACG;;qBAGM,4BAA2B"}
package/dist/client.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { t as PACKAGE_VERSION } from "./version-B5dtK-2_.mjs";
2
- //#region src/client.ts
1
+ import { t as PACKAGE_VERSION } from "./version-BXUGEOkG.mjs";
2
+ // src/client.ts
3
3
  const solanaPaymentsClient = () => ({
4
4
  id: "solanaPayments",
5
5
  version: PACKAGE_VERSION,
@@ -27,7 +27,6 @@ const solanaPaymentsClient = () => ({
27
27
  })
28
28
  } })
29
29
  });
30
- //#endregion
31
30
  export { solanaPaymentsClient };
32
31
 
33
32
  //# sourceMappingURL=client.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["import type { BetterFetch, BetterFetchOption, BetterFetchResponse } from \"@better-fetch/fetch\";\nimport type { BetterAuthClientPlugin } from \"better-auth/client\";\n\nimport type { solanaPayments as solanaPaymentsServer } from \"./index.ts\";\nimport { PACKAGE_VERSION } from \"./version.ts\";\n\nexport type FetchResult<T, O extends BetterFetchOption | undefined> = O extends { throw: true }\n ? T\n : BetterFetchResponse<T>;\n\nexport interface SolanaPaymentResponse {\n id: string;\n reference: string;\n amount: string;\n mint: string;\n decimals: number;\n recipient: string;\n status: \"pending\" | \"paid\" | \"expired\" | \"failed\";\n fulfillmentStatus?: \"pending\" | \"processing\" | \"completed\";\n expiresAt: Date;\n signature?: string;\n slot?: string;\n metadata?: Record<string, unknown>;\n paymentUrl?: string;\n}\n\nexport interface SolanaPaymentActions {\n create: <O extends BetterFetchOption | undefined = undefined>(\n data: {\n amount: string;\n metadata?: Record<string, unknown>;\n organizationId?: string;\n },\n options?: O,\n ) => Promise<FetchResult<SolanaPaymentResponse, O>>;\n verify: <O extends BetterFetchOption | undefined = undefined>(\n data: { reference: string; signature?: string; organizationId?: string },\n options?: O,\n ) => Promise<FetchResult<SolanaPaymentResponse, O>>;\n get: <O extends BetterFetchOption | undefined = undefined>(\n data: { reference: string; organizationId?: string },\n options?: O,\n ) => Promise<FetchResult<SolanaPaymentResponse, O>>;\n}\n\nexport interface SolanaPaymentsClientActions {\n payment: SolanaPaymentActions;\n}\n\ndeclare module \"better-auth/client\" {\n interface BetterAuthClient {\n payment: SolanaPaymentActions;\n }\n}\n\ndeclare module \"better-auth\" {\n interface BetterAuthClientPlugins {\n solanaPayments: ReturnType<typeof solanaPaymentsClient>;\n }\n}\n\ntype SolanaPaymentsClientPluginInstance = Omit<\n BetterAuthClientPlugin,\n \"id\" | \"$InferServerPlugin\" | \"getActions\"\n> & {\n id: \"solanaPayments\";\n $InferServerPlugin: ReturnType<typeof solanaPaymentsServer>;\n getActions: (\n $fetch: BetterFetch,\n $store: unknown,\n options: unknown,\n ) => SolanaPaymentsClientActions;\n};\n\nexport const solanaPaymentsClient = (): SolanaPaymentsClientPluginInstance => ({\n id: \"solanaPayments\",\n version: PACKAGE_VERSION,\n $InferServerPlugin: {} as ReturnType<typeof solanaPaymentsServer>,\n pathMethods: {\n \"/solana-payments/create-payment\": \"POST\",\n \"/solana-payments/verify-payment\": \"POST\",\n \"/solana-payments/payment\": \"GET\",\n },\n getActions: ($fetch): SolanaPaymentsClientActions => ({\n payment: {\n create: (data, options) =>\n $fetch(\"/solana-payments/create-payment\", {\n ...options,\n method: \"POST\",\n body: data,\n }),\n verify: (data, options) =>\n $fetch(\"/solana-payments/verify-payment\", {\n ...options,\n method: \"POST\",\n body: data,\n }),\n get: (data, options) =>\n $fetch(\"/solana-payments/payment\", { ...options, method: \"GET\", query: data }),\n },\n }),\n});\n"],"mappings":";;AA0EA,MAAa,8BAAkE;CAC7E,IAAI;CACJ,SAAS;CACT,oBAAoB,CAAC;CACrB,aAAa;EACX,mCAAmC;EACnC,mCAAmC;EACnC,4BAA4B;CAC9B;CACA,aAAa,YAAyC,EACpD,SAAS;EACP,SAAS,MAAM,YACb,OAAO,mCAAmC;GACxC,GAAG;GACH,QAAQ;GACR,MAAM;EACR,CAAC;EACH,SAAS,MAAM,YACb,OAAO,mCAAmC;GACxC,GAAG;GACH,QAAQ;GACR,MAAM;EACR,CAAC;EACH,MAAM,MAAM,YACV,OAAO,4BAA4B;GAAE,GAAG;GAAS,QAAQ;GAAO,OAAO;EAAK,CAAC;CACjF,EACF;AACF"}
1
+ {"version":3,"file":"client.mjs","names":[],"sources":["../src/client.ts"],"sourcesContent":["import type { BetterFetchOption, BetterFetchResponse } from \"@better-fetch/fetch\";\nimport type { BetterAuthClientPlugin } from \"better-auth/client\";\n\nimport type { solanaPayments as solanaPaymentsServer } from \"./index.ts\";\nimport { PACKAGE_VERSION } from \"./version.ts\";\n\nexport type FetchResult<T, O extends BetterFetchOption | undefined> = O extends { throw: true }\n ? T\n : BetterFetchResponse<T>;\n\nexport interface SolanaPaymentResponse {\n id: string;\n reference: string;\n amount: string;\n mint: string;\n decimals: number;\n recipient: string;\n status: \"pending\" | \"paid\" | \"expired\" | \"failed\";\n fulfillmentStatus?: \"pending\" | \"processing\" | \"completed\";\n expiresAt: Date;\n signature?: string;\n slot?: string;\n metadata?: Record<string, unknown>;\n paymentUrl?: string;\n}\n\nexport interface SolanaPaymentActions {\n create: <O extends BetterFetchOption | undefined = undefined>(\n data: {\n amount: string;\n metadata?: Record<string, unknown>;\n organizationId?: string;\n },\n options?: O,\n ) => Promise<FetchResult<SolanaPaymentResponse, O>>;\n verify: <O extends BetterFetchOption | undefined = undefined>(\n data: { reference: string; signature?: string; organizationId?: string },\n options?: O,\n ) => Promise<FetchResult<SolanaPaymentResponse, O>>;\n get: <O extends BetterFetchOption | undefined = undefined>(\n data: { reference: string; organizationId?: string },\n options?: O,\n ) => Promise<FetchResult<SolanaPaymentResponse, O>>;\n}\n\nexport interface SolanaPaymentsClientActions {\n payment: SolanaPaymentActions;\n}\n\ndeclare module \"better-auth/client\" {\n interface BetterAuthClient {\n payment: SolanaPaymentActions;\n }\n}\n\ndeclare module \"better-auth\" {\n interface BetterAuthClientPlugins {\n solanaPayments: ReturnType<typeof solanaPaymentsClient>;\n }\n}\n\ntype SolanaPaymentsClientPluginInstance = Omit<\n BetterAuthClientPlugin,\n \"id\" | \"version\" | \"$InferServerPlugin\" | \"getActions\"\n> & {\n id: \"solanaPayments\";\n version: typeof PACKAGE_VERSION;\n $InferServerPlugin: ReturnType<typeof solanaPaymentsServer>;\n getActions: (\n $fetch: Parameters<NonNullable<BetterAuthClientPlugin[\"getActions\"]>>[0],\n $store: unknown,\n options: unknown,\n ) => SolanaPaymentsClientActions;\n};\n\nexport const solanaPaymentsClient = (): SolanaPaymentsClientPluginInstance => ({\n id: \"solanaPayments\",\n version: PACKAGE_VERSION,\n $InferServerPlugin: {} as ReturnType<typeof solanaPaymentsServer>,\n pathMethods: {\n \"/solana-payments/create-payment\": \"POST\",\n \"/solana-payments/verify-payment\": \"POST\",\n \"/solana-payments/payment\": \"GET\",\n },\n getActions: ($fetch): SolanaPaymentsClientActions => ({\n payment: {\n create: (data, options) =>\n $fetch(\"/solana-payments/create-payment\", {\n ...options,\n method: \"POST\",\n body: data,\n }),\n verify: (data, options) =>\n $fetch(\"/solana-payments/verify-payment\", {\n ...options,\n method: \"POST\",\n body: data,\n }),\n get: (data, options) =>\n $fetch(\"/solana-payments/payment\", { ...options, method: \"GET\", query: data }),\n },\n }),\n});\n"],"mappings":";;AA2EA,MAAa,8BAAkE;CAC7E,IAAI;CACJ,SAAS;CACT,oBAAoB,CAAC;CACrB,aAAa;EACX,mCAAmC;EACnC,mCAAmC;EACnC,4BAA4B;CAC9B;CACA,aAAa,YAAyC,EACpD,SAAS;EACP,SAAS,MAAM,YACb,OAAO,mCAAmC;GACxC,GAAG;GACH,QAAQ;GACR,MAAM;EACR,CAAC;EACH,SAAS,MAAM,YACb,OAAO,mCAAmC;GACxC,GAAG;GACH,QAAQ;GACR,MAAM;EACR,CAAC;EACH,MAAM,MAAM,YACV,OAAO,4BAA4B;GAAE,GAAG;GAAS,QAAQ;GAAO,OAAO;EAAK,CAAC;CACjF,EACF;AACF"}
@@ -1,15 +1,12 @@
1
1
  import { GenericEndpointContext, InferOptionSchema } from "better-auth";
2
2
  import { AddressInput, SolanaPaymentsReadOnlyClient } from "solana-payments";
3
3
  import { BetterAuthPluginDBSchema, DBFieldAttribute } from "better-auth/db";
4
- //#region src/schema.d.ts
5
4
  type SolanaPaymentSchema = Record<"solanaPayment", {
6
5
  fields: Record<"reference" | "referenceType" | "referenceId" | "amount" | "mint" | "decimals" | "recipient" | "status" | "fulfillmentStatus" | "fulfillmentToken" | "fulfillmentClaimedAt" | "expiresAt" | "signature" | "slot" | "metadata" | "createdAt" | "updatedAt", DBFieldAttribute>;
7
6
  }>;
8
7
  type SolanaPaymentsPluginSchema = SolanaPaymentSchema;
9
8
  declare const solanaPaymentsPluginSchema: SolanaPaymentSchema;
10
9
  declare function getSchema(options: Pick<SolanaPaymentsOptions, "schema">): BetterAuthPluginDBSchema;
11
- //#endregion
12
- //#region src/types.d.ts
13
10
  type SolanaPaymentStatus = "pending" | "paid" | "expired" | "failed";
14
11
  interface SolanaPayment {
15
12
  id: string;
@@ -43,11 +40,7 @@ interface SolanaPaymentsOptions {
43
40
  };
44
41
  schema?: InferOptionSchema<SolanaPaymentsPluginSchema>;
45
42
  }
46
- //#endregion
47
- //#region src/version.d.ts
48
- declare const PACKAGE_VERSION = "0.4.0";
49
- //#endregion
50
- //#region src/store.d.ts
43
+ declare const PACKAGE_VERSION = "0.5.0";
51
44
  type Adapter = {
52
45
  create<T>(input: {
53
46
  model: string;
@@ -63,10 +56,14 @@ type Adapter = {
63
56
  where: WhereClause;
64
57
  }): Promise<T | null>;
65
58
  };
66
- type WhereClause = {
59
+ type WhereClause = ({
67
60
  field: string;
68
61
  value: string | null;
69
- }[];
62
+ } | {
63
+ field: string;
64
+ operator: "in";
65
+ value: string[];
66
+ })[];
70
67
  interface SolanaPaymentStoreContext {
71
68
  adapter: Adapter;
72
69
  session?: {
@@ -92,17 +89,15 @@ interface SolanaPaymentStore {
92
89
  findById(id: string): Promise<SolanaPayment | null>;
93
90
  findByReference(reference: string): Promise<SolanaPayment | null>;
94
91
  markPaid(reference: string, input?: MarkPaidInput): Promise<SolanaPayment | null>;
95
- markPaidWithTransition(reference: string, input?: MarkPaidInput): Promise<MarkPaidResult>;
92
+ markPaidWithTransition(reference: string, input?: MarkPaidInput, recoverExpired?: boolean): Promise<MarkPaidResult>;
96
93
  claimFulfillment(reference: string): Promise<SolanaPayment | null>;
97
94
  finishFulfillment(reference: string, token: string, completed: boolean): Promise<SolanaPayment | null>;
98
95
  markExpired(reference: string): Promise<SolanaPayment | null>;
99
96
  }
100
97
  declare function createSolanaPaymentStore(context: SolanaPaymentStoreContext): SolanaPaymentStore;
101
- //#endregion
102
- //#region src/index.d.ts
103
98
  declare function solanaPayments(input: SolanaPaymentsOptions): {
104
99
  id: "solanaPayments";
105
- version: string;
100
+ version: "0.5.0";
106
101
  endpoints: {
107
102
  createPayment: import("better-auth").StrictEndpoint<"/solana-payments/create-payment", {
108
103
  method: "POST";
@@ -111,7 +106,7 @@ declare function solanaPayments(input: SolanaPaymentsOptions): {
111
106
  metadata: import("zod").ZodOptional<import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnknown>>;
112
107
  organizationId: import("zod").ZodOptional<import("zod").ZodString>;
113
108
  }, import("zod/v4/core").$strip>;
114
- use: (import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
109
+ use: (import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>> | import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
115
110
  session: {
116
111
  session: Record<string, any> & {
117
112
  id: string;
@@ -133,9 +128,8 @@ declare function solanaPayments(input: SolanaPaymentsOptions): {
133
128
  image?: string | null | undefined;
134
129
  };
135
130
  };
136
- }>> | import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>>)[];
131
+ }>>)[];
137
132
  }, {
138
- paymentUrl?: string | undefined;
139
133
  id: string;
140
134
  reference: string;
141
135
  amount: string;
@@ -143,11 +137,12 @@ declare function solanaPayments(input: SolanaPaymentsOptions): {
143
137
  decimals: number;
144
138
  recipient: string;
145
139
  status: SolanaPaymentStatus;
146
- fulfillmentStatus: "pending" | "processing" | "completed";
140
+ fulfillmentStatus: "completed" | "pending" | "processing";
147
141
  expiresAt: Date;
148
142
  signature: string | undefined;
149
143
  slot: string | undefined;
150
144
  metadata: Record<string, unknown> | undefined;
145
+ paymentUrl?: string | undefined;
151
146
  }>;
152
147
  verifyPayment: import("better-auth").StrictEndpoint<"/solana-payments/verify-payment", {
153
148
  method: "POST";
@@ -156,7 +151,7 @@ declare function solanaPayments(input: SolanaPaymentsOptions): {
156
151
  signature: import("zod").ZodOptional<import("zod").ZodString>;
157
152
  organizationId: import("zod").ZodOptional<import("zod").ZodString>;
158
153
  }, import("zod/v4/core").$strip>;
159
- use: (import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
154
+ use: (import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>> | import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<{
160
155
  session: {
161
156
  session: Record<string, any> & {
162
157
  id: string;
@@ -178,9 +173,8 @@ declare function solanaPayments(input: SolanaPaymentsOptions): {
178
173
  image?: string | null | undefined;
179
174
  };
180
175
  };
181
- }>> | import("better-auth").Middleware<import("better-auth").MiddlewareOptions, (inputContext: import("better-auth").MiddlewareInputContext<import("better-auth").MiddlewareOptions>) => Promise<void>>)[];
176
+ }>>)[];
182
177
  }, {
183
- paymentUrl?: string | undefined;
184
178
  id: string;
185
179
  reference: string;
186
180
  amount: string;
@@ -188,11 +182,12 @@ declare function solanaPayments(input: SolanaPaymentsOptions): {
188
182
  decimals: number;
189
183
  recipient: string;
190
184
  status: SolanaPaymentStatus;
191
- fulfillmentStatus: "pending" | "processing" | "completed";
185
+ fulfillmentStatus: "completed" | "pending" | "processing";
192
186
  expiresAt: Date;
193
187
  signature: string | undefined;
194
188
  slot: string | undefined;
195
189
  metadata: Record<string, unknown> | undefined;
190
+ paymentUrl?: string | undefined;
196
191
  }>;
197
192
  getPayment: import("better-auth").StrictEndpoint<"/solana-payments/payment", {
198
193
  method: "GET";
@@ -224,7 +219,6 @@ declare function solanaPayments(input: SolanaPaymentsOptions): {
224
219
  };
225
220
  }>>[];
226
221
  }, {
227
- paymentUrl?: string | undefined;
228
222
  id: string;
229
223
  reference: string;
230
224
  amount: string;
@@ -232,23 +226,23 @@ declare function solanaPayments(input: SolanaPaymentsOptions): {
232
226
  decimals: number;
233
227
  recipient: string;
234
228
  status: SolanaPaymentStatus;
235
- fulfillmentStatus: "pending" | "processing" | "completed";
229
+ fulfillmentStatus: "completed" | "pending" | "processing";
236
230
  expiresAt: Date;
237
231
  signature: string | undefined;
238
232
  slot: string | undefined;
239
233
  metadata: Record<string, unknown> | undefined;
234
+ paymentUrl?: string | undefined;
240
235
  }>;
241
236
  };
242
237
  schema: import("better-auth").BetterAuthPluginDBSchema;
243
238
  $ERROR_CODES: {
239
+ INVALID_PAYMENT: import("better-auth").RawError<"INVALID_PAYMENT">;
244
240
  MISSING_SESSION: import("better-auth").RawError<"MISSING_SESSION">;
245
- UNAUTHORIZED_PAYMENT: import("better-auth").RawError<"UNAUTHORIZED_PAYMENT">;
246
241
  PAYMENT_EXPIRED: import("better-auth").RawError<"PAYMENT_EXPIRED">;
247
- INVALID_PAYMENT: import("better-auth").RawError<"INVALID_PAYMENT">;
248
242
  PAYMENT_MISMATCH: import("better-auth").RawError<"PAYMENT_MISMATCH">;
249
243
  PAYMENT_PROVIDER_UNAVAILABLE: import("better-auth").RawError<"PAYMENT_PROVIDER_UNAVAILABLE">;
244
+ UNAUTHORIZED_PAYMENT: import("better-auth").RawError<"UNAUTHORIZED_PAYMENT">;
250
245
  };
251
246
  };
252
- //#endregion
253
247
  export { SolanaPaymentStore as a, PACKAGE_VERSION as c, SolanaPaymentsOptions as d, getSchema as f, MarkPaidResult as i, SolanaPayment as l, CreateSolanaPaymentInput as n, SolanaPaymentStoreContext as o, solanaPaymentsPluginSchema as p, MarkPaidInput as r, createSolanaPaymentStore as s, solanaPayments as t, SolanaPaymentStatus as u };
254
- //# sourceMappingURL=index-DlPQtl6v.d.mts.map
248
+ //# sourceMappingURL=index-BQ-nihZA.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-BQ-nihZA.d.mts","names":[],"sources":["../src/schema.ts","../src/types.ts","../src/version.ts","../src/store.ts","../src/index.ts"],"mappings":";;;KAIK,sBAAsB;EAGvB,QAAQ,kQAkBN;;KA6BM,6BAA6B;cAC5B,4BAA4B;iBAEzB,UACd,SAAS,KAAK,mCACb;KCtDS;UAEK;EACf;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA,uBAAuB;EACvB,WAAW;EACX;;EAEA;EACA;EACA,WAAW;EACX,WAAW;;UAGI;EACf,QAAQ;EACR,WAAW;EACX;EACA,qBACE,SAAS,eACT,SAAS,2BACN;EACL;IACE;;EAEF,SAAS,kBAAkB;;cCzChB;KCMR;EACH,OAAO,GAAG;IAAS;IAAe,MAAM,KAAK;MAAa,QAAQ;EAClE,QAAQ,GAAG;IAAS;IAAe,OAAO;MAAgB,QAAQ;EAClE,OAAO,GAAG;IAAS;IAAe,QAAQ,QAAQ;IAAI,OAAO;MAAgB,QAAQ;;KAElF;EACC;EAAe;;EACf;EAAe;EAAgB;;UAGpB;EACf,SAAS;EACT;IAAY;MAAS;;;EACrB;EACA;;KAGU,2BAA2B,KACrC;UAIe;EACf;EACA;;UAGe;EACf,SAAS;EACT;;UAGe;EACf,eAAe;EACf,OAAO,OAAO,2BAA2B,QAAQ;EACjD,SAAS,aAAa,QAAQ;EAC9B,gBAAgB,oBAAoB,QAAQ;EAC5C,SAAS,mBAAmB,QAAQ,gBAAgB,QAAQ;EAC5D,uBACE,mBACA,QAAQ,eACR,2BACC,QAAQ;EACX,iBAAiB,oBAAoB,QAAQ;EAC7C,kBACE,mBACA,eACA,qBACC,QAAQ;EACX,YAAY,oBAAoB,QAAQ;;iBAG1B,yBAAyB,SAAS,4BAA4B;iBC7B9D,eAAe,OAAO;;;;IAgBhC,qCAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IACb,qCAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IACb,kCAAU"}
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as SolanaPaymentStore, c as PACKAGE_VERSION, d as SolanaPaymentsOptions, f as getSchema, i as MarkPaidResult, l as SolanaPayment, n as CreateSolanaPaymentInput, o as SolanaPaymentStoreContext, p as solanaPaymentsPluginSchema, r as MarkPaidInput, s as createSolanaPaymentStore, t as solanaPayments, u as SolanaPaymentStatus } from "./index-DlPQtl6v.mjs";
1
+ import { a as SolanaPaymentStore, c as PACKAGE_VERSION, d as SolanaPaymentsOptions, f as getSchema, i as MarkPaidResult, l as SolanaPayment, n as CreateSolanaPaymentInput, o as SolanaPaymentStoreContext, p as solanaPaymentsPluginSchema, r as MarkPaidInput, s as createSolanaPaymentStore, t as solanaPayments, u as SolanaPaymentStatus } from "./index-BQ-nihZA.mjs";
2
2
  export { type CreateSolanaPaymentInput, type MarkPaidInput, type MarkPaidResult, PACKAGE_VERSION, type SolanaPayment, type SolanaPaymentStatus, type SolanaPaymentStore, type SolanaPaymentStoreContext, type SolanaPaymentsOptions, createSolanaPaymentStore, getSchema, solanaPayments, solanaPaymentsPluginSchema };
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- import { t as PACKAGE_VERSION } from "./version-B5dtK-2_.mjs";
1
+ import { t as PACKAGE_VERSION } from "./version-BXUGEOkG.mjs";
2
2
  import { defineErrorCodes } from "better-auth";
3
3
  import { randomBytes, randomUUID } from "node:crypto";
4
4
  import { APIError, createAuthEndpoint, getSessionFromCtx, originCheckMiddleware, sessionMiddleware } from "better-auth/api";
5
5
  import { formatTokenAmount, isSolanaPaymentsError } from "solana-payments";
6
6
  import { z } from "zod";
7
7
  import { mergeSchema } from "better-auth/db";
8
- //#region src/store.ts
8
+ // src/store.ts
9
9
  const SOLANA_PAYMENT_MODEL = "solanaPayment";
10
10
  function createSolanaPaymentStore(context) {
11
11
  const getOwner = async () => {
@@ -52,7 +52,7 @@ function createSolanaPaymentStore(context) {
52
52
  value: reference
53
53
  }])
54
54
  });
55
- const markPaidWithTransition = async (reference, input = {}) => {
55
+ const markPaidWithTransition = async (reference, input = {}, recoverExpired = false) => {
56
56
  const payment = await findByReference(reference);
57
57
  if (!payment) return {
58
58
  payment: null,
@@ -62,10 +62,23 @@ function createSolanaPaymentStore(context) {
62
62
  payment,
63
63
  transitioned: false
64
64
  };
65
- if (payment.status !== "pending") return {
65
+ if (payment.status !== "pending" && !(recoverExpired && payment.status === "expired")) return {
66
66
  payment: null,
67
67
  transitioned: false
68
68
  };
69
+ if (input.signature) {
70
+ const existing = await context.adapter.findOne({
71
+ model: SOLANA_PAYMENT_MODEL,
72
+ where: [{
73
+ field: "signature",
74
+ value: input.signature
75
+ }]
76
+ });
77
+ if (existing && existing.id !== payment.id) return {
78
+ payment: null,
79
+ transitioned: false
80
+ };
81
+ }
69
82
  const updated = await context.adapter.update({
70
83
  model: SOLANA_PAYMENT_MODEL,
71
84
  update: {
@@ -76,7 +89,11 @@ function createSolanaPaymentStore(context) {
76
89
  where: await paymentWhere([{
77
90
  field: "id",
78
91
  value: payment.id
79
- }, {
92
+ }, recoverExpired ? {
93
+ field: "status",
94
+ operator: "in",
95
+ value: ["pending", "expired"]
96
+ } : {
80
97
  field: "status",
81
98
  value: "pending"
82
99
  }])
@@ -198,8 +215,7 @@ function createSolanaPaymentStore(context) {
198
215
  }
199
216
  };
200
217
  }
201
- //#endregion
202
- //#region src/routes.ts
218
+ // src/routes.ts
203
219
  const createPaymentBody = z.object({
204
220
  amount: z.string().min(1),
205
221
  metadata: z.record(z.string(), z.unknown()).optional(),
@@ -232,7 +248,7 @@ async function paymentStore(ctx, organizationId) {
232
248
  adapter: ctx.context.adapter,
233
249
  session,
234
250
  organizationId,
235
- hasOrganizationPlugin: ctx.context.hasPlugin?.("organization") === true
251
+ hasOrganizationPlugin: ctx.context.options.plugins?.some((plugin) => plugin.id === "organization") === true
236
252
  });
237
253
  await store.assertOwner();
238
254
  return store;
@@ -336,11 +352,13 @@ const verifyPayment = (options, path = "/verify-payment") => createAuthEndpoint(
336
352
  assertOrganizationEnabled(options, ctx.body.organizationId);
337
353
  const { store, payment } = await loadPayment(ctx, ctx.body.reference, ctx.body.organizationId);
338
354
  if (payment.status === "paid") return ctx.json(asResponse(await fulfillPayment(ctx, options, store, payment)));
339
- if (payment.status === "expired" || payment.expiresAt <= /* @__PURE__ */ new Date()) {
340
- if (payment.status === "pending") await store.markExpired(payment.reference);
341
- routeError("PAYMENT_EXPIRED", "Payment intent has expired.");
342
- }
343
- if (payment.status !== "pending") routeError("INVALID_PAYMENT", "Payment is not pending.");
355
+ if (payment.status !== "pending" && payment.status !== "expired") routeError("INVALID_PAYMENT", "Payment cannot be settled.");
356
+ const configuredRequest = options.client.payments.createRequest({
357
+ amount: formatTokenAmount(payment.amount, payment.decimals),
358
+ recipient: payment.recipient,
359
+ reference: payment.reference
360
+ });
361
+ if (configuredRequest.mint !== payment.mint || configuredRequest.decimals !== payment.decimals) routeError("PAYMENT_MISMATCH", "Payment asset configuration changed.");
344
362
  let verified;
345
363
  try {
346
364
  verified = await options.client.payments.verify({
@@ -357,11 +375,27 @@ const verifyPayment = (options, path = "/verify-payment") => createAuthEndpoint(
357
375
  ].includes(error.code)) routeError("PAYMENT_PROVIDER_UNAVAILABLE", "Solana RPC could not confirm the payment. Retry verification with the same reference.");
358
376
  routeError("PAYMENT_MISMATCH", error instanceof Error ? error.message : "Payment did not match intent.");
359
377
  }
360
- if (!verified.found || verified.reference !== payment.reference || verified.recipient !== payment.recipient || verified.amount?.toString() !== payment.amount) routeError("PAYMENT_MISMATCH", "Payment did not exactly match the stored intent.");
378
+ const expired = payment.status === "expired" || payment.expiresAt.getTime() <= Date.now();
379
+ if (expired && !verified.found) {
380
+ await store.markExpired(payment.reference);
381
+ routeError("PAYMENT_EXPIRED", "Payment intent has expired.");
382
+ }
383
+ if (!verified.found || verified.reference !== payment.reference || verified.recipient !== payment.recipient || !verified.signature || verified.amount?.toString() !== payment.amount) routeError("PAYMENT_MISMATCH", "Payment did not exactly match the stored intent.");
384
+ if (verified.confirmationStatus !== "finalized") routeError("PAYMENT_PROVIDER_UNAVAILABLE", "Payment is awaiting finality. Retry verification.");
385
+ if (expired) {
386
+ const rpc = await options.client.transactions.retrieve({ signature: verified.signature }).catch(() => routeError("PAYMENT_PROVIDER_UNAVAILABLE", "Could not verify the transfer time. Retry verification."));
387
+ const transaction = rpc.transaction;
388
+ const blockTime = typeof transaction === "object" && transaction !== null && "blockTime" in transaction ? transaction.blockTime : void 0;
389
+ const seconds = typeof blockTime === "bigint" ? Number(blockTime) : blockTime;
390
+ if (rpc.signature !== verified.signature || rpc.confirmationStatus !== "finalized" || rpc.err != null || verified.slot != null && rpc.slot !== verified.slot || typeof seconds !== "number" || !Number.isSafeInteger(seconds) || seconds < Math.floor(payment.createdAt.getTime() / 1e3) || seconds * 1e3 >= payment.expiresAt.getTime()) {
391
+ await store.markExpired(payment.reference);
392
+ routeError("PAYMENT_EXPIRED", "No finalized transfer was recorded within the payment window.");
393
+ }
394
+ }
361
395
  const { payment: paid } = await store.markPaidWithTransition(payment.reference, {
362
396
  signature: verified.signature,
363
397
  slot: verified.slot?.toString()
364
- });
398
+ }, expired);
365
399
  if (!paid) routeError("INVALID_PAYMENT", "Payment state could not be updated.");
366
400
  return ctx.json(asResponse(await fulfillPayment(ctx, options, store, paid)));
367
401
  });
@@ -375,8 +409,7 @@ const getPayment = (options, path = "/payment") => createAuthEndpoint(path, {
375
409
  const current = payment.status === "pending" && payment.expiresAt <= /* @__PURE__ */ new Date() ? await store.markExpired(payment.reference) : payment;
376
410
  return ctx.json(asResponse(current ?? payment));
377
411
  });
378
- //#endregion
379
- //#region src/schema.ts
412
+ // src/schema.ts
380
413
  const solanaPaymentSchema = { solanaPayment: { fields: {
381
414
  reference: {
382
415
  type: "string",
@@ -457,8 +490,7 @@ const solanaPaymentsPluginSchema = solanaPaymentSchema;
457
490
  function getSchema(options) {
458
491
  return mergeSchema(solanaPaymentSchema, options.schema);
459
492
  }
460
- //#endregion
461
- //#region src/index.ts
493
+ // src/index.ts
462
494
  const ERROR_CODES = defineErrorCodes({
463
495
  MISSING_SESSION: "An authenticated session is required.",
464
496
  UNAUTHORIZED_PAYMENT: "Payment was not found for this owner.",
@@ -491,7 +523,6 @@ function solanaPayments(input) {
491
523
  $ERROR_CODES: ERROR_CODES
492
524
  };
493
525
  }
494
- //#endregion
495
526
  export { PACKAGE_VERSION, createSolanaPaymentStore, getSchema, solanaPayments, solanaPaymentsPluginSchema };
496
527
 
497
528
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/store.ts","../src/routes.ts","../src/schema.ts","../src/index.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nimport type { SolanaPayment } from \"./types.ts\";\n\nconst SOLANA_PAYMENT_MODEL = \"solanaPayment\";\n\ntype Adapter = {\n create<T>(input: { model: string; data: Omit<T, \"id\"> }): Promise<T>;\n findOne<T>(input: { model: string; where: WhereClause }): Promise<T | null>;\n update<T>(input: { model: string; update: Partial<T>; where: WhereClause }): Promise<T | null>;\n};\ntype WhereClause = { field: string; value: string | null }[];\n\nexport interface SolanaPaymentStoreContext {\n adapter: Adapter;\n session?: { user?: { id: string } | null } | null;\n organizationId?: string;\n hasOrganizationPlugin?: boolean;\n}\n\nexport type CreateSolanaPaymentInput = Omit<\n SolanaPayment,\n \"id\" | \"referenceType\" | \"referenceId\" | \"status\" | \"createdAt\" | \"updatedAt\"\n>;\n\nexport interface MarkPaidInput {\n signature?: string;\n slot?: string;\n}\n\nexport interface MarkPaidResult {\n payment: SolanaPayment | null;\n transitioned: boolean;\n}\n\nexport interface SolanaPaymentStore {\n assertOwner(): Promise<void>;\n create(input: CreateSolanaPaymentInput): Promise<SolanaPayment>;\n findById(id: string): Promise<SolanaPayment | null>;\n findByReference(reference: string): Promise<SolanaPayment | null>;\n markPaid(reference: string, input?: MarkPaidInput): Promise<SolanaPayment | null>;\n markPaidWithTransition(reference: string, input?: MarkPaidInput): Promise<MarkPaidResult>;\n claimFulfillment(reference: string): Promise<SolanaPayment | null>;\n finishFulfillment(\n reference: string,\n token: string,\n completed: boolean,\n ): Promise<SolanaPayment | null>;\n markExpired(reference: string): Promise<SolanaPayment | null>;\n}\n\nexport function createSolanaPaymentStore(context: SolanaPaymentStoreContext): SolanaPaymentStore {\n const getOwner = async (): Promise<{ type: \"user\" | \"organization\"; id: string }> => {\n const userId = context.session?.user?.id;\n if (!userId) throw new Error(\"A session user is required to access Solana payments\");\n\n if (!context.organizationId) return { type: \"user\", id: userId };\n if (!context.hasOrganizationPlugin) {\n throw new Error(\"The Better Auth organization plugin is required for organization payments\");\n }\n\n const member = await context.adapter.findOne<{ id: string }>({\n model: \"member\",\n where: [\n { field: \"organizationId\", value: context.organizationId },\n { field: \"userId\", value: userId },\n ],\n });\n if (!member) throw new Error(\"The session user must be an organization member\");\n return { type: \"organization\", id: context.organizationId };\n };\n\n const paymentWhere = async (where: WhereClause): Promise<WhereClause> => {\n const owner = await getOwner();\n return [\n ...where,\n { field: \"referenceType\", value: owner.type },\n { field: \"referenceId\", value: owner.id },\n ];\n };\n\n const findByReference = async (reference: string): Promise<SolanaPayment | null> =>\n context.adapter.findOne<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n where: await paymentWhere([{ field: \"reference\", value: reference }]),\n });\n\n const markPaidWithTransition = async (\n reference: string,\n input: MarkPaidInput = {},\n ): Promise<MarkPaidResult> => {\n const payment = await findByReference(reference);\n if (!payment) return { payment: null, transitioned: false };\n if (payment.status === \"paid\") return { payment, transitioned: false };\n if (payment.status !== \"pending\") return { payment: null, transitioned: false };\n const updated = await context.adapter.update<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n update: { status: \"paid\", ...input, updatedAt: new Date() },\n where: await paymentWhere([\n { field: \"id\", value: payment.id },\n { field: \"status\", value: \"pending\" },\n ]),\n });\n if (updated) return { payment: updated, transitioned: true };\n const current = await findByReference(reference);\n return { payment: current?.status === \"paid\" ? current : null, transitioned: false };\n };\n\n return {\n async assertOwner() {\n await getOwner();\n },\n async create(input) {\n const owner = await getOwner();\n const now = new Date();\n return context.adapter.create<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n data: {\n ...input,\n referenceType: owner.type,\n referenceId: owner.id,\n status: \"pending\",\n fulfillmentStatus: \"pending\",\n fulfillmentToken: null,\n fulfillmentClaimedAt: null,\n createdAt: now,\n updatedAt: now,\n },\n });\n },\n findById: async (id) =>\n context.adapter.findOne<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n where: await paymentWhere([{ field: \"id\", value: id }]),\n }),\n findByReference,\n async markPaid(reference, input = {}) {\n return (await markPaidWithTransition(reference, input)).payment;\n },\n markPaidWithTransition,\n async claimFulfillment(reference) {\n const payment = await findByReference(reference);\n if (\n !payment ||\n payment.status !== \"paid\" ||\n !payment.fulfillmentStatus ||\n payment.fulfillmentStatus === \"completed\"\n )\n return null;\n if (\n payment.fulfillmentStatus === \"processing\" &&\n payment.fulfillmentClaimedAt &&\n new Date(payment.fulfillmentClaimedAt).getTime() > Date.now() - 5 * 60_000\n )\n return null;\n return context.adapter.update<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n where: await paymentWhere([\n { field: \"id\", value: payment.id },\n { field: \"fulfillmentStatus\", value: payment.fulfillmentStatus },\n { field: \"fulfillmentToken\", value: payment.fulfillmentToken ?? null },\n ]),\n update: {\n fulfillmentStatus: \"processing\",\n fulfillmentToken: randomUUID(),\n fulfillmentClaimedAt: new Date(),\n updatedAt: new Date(),\n },\n });\n },\n async finishFulfillment(reference, token, completed) {\n return context.adapter.update<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n where: await paymentWhere([\n { field: \"reference\", value: reference },\n { field: \"fulfillmentToken\", value: token },\n { field: \"fulfillmentStatus\", value: \"processing\" },\n ]),\n update: {\n fulfillmentStatus: completed ? \"completed\" : \"pending\",\n fulfillmentToken: null,\n fulfillmentClaimedAt: null,\n updatedAt: new Date(),\n },\n });\n },\n async markExpired(reference) {\n const payment = await findByReference(reference);\n if (!payment || payment.status !== \"pending\")\n return payment?.status === \"expired\" ? payment : null;\n\n return context.adapter.update<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n update: { status: \"expired\", updatedAt: new Date() },\n where: await paymentWhere([\n { field: \"id\", value: payment.id },\n { field: \"status\", value: \"pending\" },\n ]),\n });\n },\n };\n}\n","import { randomBytes } from \"node:crypto\";\n\nimport {\n APIError,\n createAuthEndpoint,\n getSessionFromCtx,\n originCheckMiddleware,\n sessionMiddleware,\n} from \"better-auth/api\";\nimport type { GenericEndpointContext } from \"better-auth\";\nimport { formatTokenAmount, isSolanaPaymentsError } from \"solana-payments\";\nimport { z } from \"zod\";\n\nimport { createSolanaPaymentStore } from \"./store.ts\";\nimport type { SolanaPayment, SolanaPaymentsOptions } from \"./types.ts\";\n\nconst createPaymentBody = z.object({\n amount: z.string().min(1),\n metadata: z.record(z.string(), z.unknown()).optional(),\n organizationId: z.string().min(1).optional(),\n});\nconst verifyPaymentBody = z.object({\n reference: z.string().min(1),\n /** Transaction signature lets the SDK verify a candidate before scanning recent history. */\n signature: z.string().min(1).optional(),\n organizationId: z.string().min(1).optional(),\n});\nconst getPaymentQuery = z.object({\n reference: z.string().min(1),\n organizationId: z.string().min(1).optional(),\n});\n\nfunction routeError(\n code:\n | \"MISSING_SESSION\"\n | \"UNAUTHORIZED_PAYMENT\"\n | \"PAYMENT_EXPIRED\"\n | \"INVALID_PAYMENT\"\n | \"PAYMENT_MISMATCH\"\n | \"PAYMENT_PROVIDER_UNAVAILABLE\",\n message: string,\n): never {\n const status =\n code === \"MISSING_SESSION\"\n ? \"UNAUTHORIZED\"\n : code === \"PAYMENT_PROVIDER_UNAVAILABLE\"\n ? \"INTERNAL_SERVER_ERROR\"\n : \"BAD_REQUEST\";\n throw new APIError(status, {\n code,\n message,\n });\n}\n\nfunction assertOrganizationEnabled(options: SolanaPaymentsOptions, organizationId?: string) {\n if (organizationId && options.organization?.enabled !== true) {\n routeError(\"UNAUTHORIZED_PAYMENT\", \"Organization payments are not enabled.\");\n }\n}\n\nasync function paymentStore(ctx: GenericEndpointContext, organizationId?: string) {\n const session = await getSessionFromCtx(ctx);\n if (!session) routeError(\"MISSING_SESSION\", \"An authenticated session is required.\");\n try {\n const store = createSolanaPaymentStore({\n adapter: ctx.context.adapter,\n session,\n organizationId,\n hasOrganizationPlugin: ctx.context.hasPlugin?.(\"organization\") === true,\n });\n await store.assertOwner();\n return store;\n } catch (error) {\n routeError(\n \"UNAUTHORIZED_PAYMENT\",\n error instanceof Error ? error.message : \"Unauthorized payment.\",\n );\n }\n}\n\nasync function loadPayment(\n ctx: GenericEndpointContext,\n reference: string,\n organizationId?: string,\n) {\n const store = await paymentStore(ctx, organizationId);\n try {\n const payment = await store.findByReference(reference);\n if (!payment) routeError(\"UNAUTHORIZED_PAYMENT\", \"Payment was not found for this owner.\");\n return { store, payment };\n } catch (error) {\n if (error instanceof APIError) throw error;\n routeError(\n \"UNAUTHORIZED_PAYMENT\",\n error instanceof Error ? error.message : \"Unauthorized payment.\",\n );\n }\n}\n\nfunction asResponse(payment: SolanaPayment, paymentUrl?: string) {\n return {\n id: payment.id,\n reference: payment.reference,\n amount: payment.amount,\n mint: payment.mint,\n decimals: payment.decimals,\n recipient: payment.recipient,\n status: payment.status,\n fulfillmentStatus:\n payment.fulfillmentStatus ?? (payment.status === \"paid\" ? \"completed\" : \"pending\"),\n expiresAt: payment.expiresAt,\n signature: payment.signature ?? undefined,\n slot: payment.slot ?? undefined,\n metadata: payment.metadata\n ? (JSON.parse(payment.metadata) as Record<string, unknown>)\n : undefined,\n ...(paymentUrl ? { paymentUrl } : {}),\n };\n}\n\n// Solana Pay references are public keys (base58-encoded 32-byte values).\nfunction createReference() {\n const bytes = randomBytes(32);\n const alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n let number = BigInt(`0x${bytes.toString(\"hex\")}`);\n let encoded = \"\";\n while (number > 0n) {\n encoded = alphabet[Number(number % 58n)] + encoded;\n number /= 58n;\n }\n for (const byte of bytes) {\n if (byte !== 0) break;\n encoded = \"1\" + encoded;\n }\n return encoded;\n}\n\nasync function fulfillPayment(\n ctx: GenericEndpointContext,\n options: SolanaPaymentsOptions,\n store: Awaited<ReturnType<typeof paymentStore>>,\n payment: SolanaPayment,\n) {\n const claimed = await store.claimFulfillment(payment.reference);\n if (!claimed) return (await store.findByReference(payment.reference)) ?? payment;\n const token = claimed.fulfillmentToken!;\n try {\n await options.onPaymentComplete?.(claimed, ctx);\n const completed = await store.finishFulfillment(claimed.reference, token, true);\n if (!completed) throw new Error(\"Fulfillment lease was lost; retry verification.\");\n return completed;\n } catch (error) {\n await store.finishFulfillment(claimed.reference, token, false);\n throw error;\n }\n}\n\nexport const createPayment = <P extends string = \"/create-payment\">(\n options: SolanaPaymentsOptions,\n path: P = \"/create-payment\" as P,\n) =>\n createAuthEndpoint(\n path,\n { method: \"POST\", body: createPaymentBody, use: [sessionMiddleware, originCheckMiddleware] },\n async (ctx) => {\n assertOrganizationEnabled(options, ctx.body.organizationId);\n const store = await paymentStore(ctx, ctx.body.organizationId);\n const reference = createReference();\n const request = options.client.payments.createRequest({\n amount: ctx.body.amount,\n recipient: options.recipient,\n reference,\n metadata: ctx.body.metadata,\n });\n const payment = await store.create({\n reference: request.reference,\n amount: request.amount.toString(),\n mint: request.mint,\n decimals: request.decimals,\n recipient: request.recipient ?? options.recipient,\n expiresAt: new Date(Date.now() + (options.paymentExpirationMs ?? 30 * 60 * 1000)),\n metadata: ctx.body.metadata ? JSON.stringify(ctx.body.metadata) : null,\n signature: null,\n slot: null,\n });\n const paymentUrl = options.client.payments.toSolanaPayUrl(request).toString();\n return ctx.json(asResponse(payment, paymentUrl));\n },\n );\n\nexport const verifyPayment = <P extends string = \"/verify-payment\">(\n options: SolanaPaymentsOptions,\n path: P = \"/verify-payment\" as P,\n) =>\n createAuthEndpoint(\n path,\n { method: \"POST\", body: verifyPaymentBody, use: [sessionMiddleware, originCheckMiddleware] },\n async (ctx) => {\n assertOrganizationEnabled(options, ctx.body.organizationId);\n const { store, payment } = await loadPayment(\n ctx,\n ctx.body.reference,\n ctx.body.organizationId,\n );\n if (payment.status === \"paid\")\n return ctx.json(asResponse(await fulfillPayment(ctx, options, store, payment)));\n if (payment.status === \"expired\" || payment.expiresAt <= new Date()) {\n if (payment.status === \"pending\") await store.markExpired(payment.reference);\n routeError(\"PAYMENT_EXPIRED\", \"Payment intent has expired.\");\n }\n if (payment.status !== \"pending\") routeError(\"INVALID_PAYMENT\", \"Payment is not pending.\");\n\n let verified;\n try {\n verified = await options.client.payments.verify({\n reference: payment.reference,\n ...(ctx.body.signature ? { signature: ctx.body.signature } : {}),\n recipient: payment.recipient,\n amount: formatTokenAmount(payment.amount, payment.decimals),\n });\n } catch (error) {\n if (\n isSolanaPaymentsError(error) &&\n [\"RPC_ERROR\", \"RPC_TIMEOUT\", \"TRANSACTION_TIMEOUT\"].includes(error.code)\n ) {\n routeError(\n \"PAYMENT_PROVIDER_UNAVAILABLE\",\n \"Solana RPC could not confirm the payment. Retry verification with the same reference.\",\n );\n }\n routeError(\n \"PAYMENT_MISMATCH\",\n error instanceof Error ? error.message : \"Payment did not match intent.\",\n );\n }\n if (\n !verified.found ||\n verified.reference !== payment.reference ||\n verified.recipient !== payment.recipient ||\n verified.amount?.toString() !== payment.amount\n ) {\n routeError(\"PAYMENT_MISMATCH\", \"Payment did not exactly match the stored intent.\");\n }\n const { payment: paid } = await store.markPaidWithTransition(payment.reference, {\n signature: verified.signature,\n slot: verified.slot?.toString(),\n });\n if (!paid) routeError(\"INVALID_PAYMENT\", \"Payment state could not be updated.\");\n return ctx.json(asResponse(await fulfillPayment(ctx, options, store, paid)));\n },\n );\n\nexport const getPayment = <P extends string = \"/payment\">(\n options: SolanaPaymentsOptions,\n path: P = \"/payment\" as P,\n) =>\n createAuthEndpoint(\n path,\n { method: \"GET\", query: getPaymentQuery, use: [sessionMiddleware] },\n async (ctx) => {\n assertOrganizationEnabled(options, ctx.query.organizationId);\n const { store, payment } = await loadPayment(\n ctx,\n ctx.query.reference,\n ctx.query.organizationId,\n );\n const current =\n payment.status === \"pending\" && payment.expiresAt <= new Date()\n ? await store.markExpired(payment.reference)\n : payment;\n return ctx.json(asResponse(current ?? payment));\n },\n );\n","import { mergeSchema, type BetterAuthPluginDBSchema, type DBFieldAttribute } from \"better-auth/db\";\n\nimport type { SolanaPaymentsOptions } from \"./types.ts\";\n\ntype SolanaPaymentSchema = Record<\n \"solanaPayment\",\n {\n fields: Record<\n | \"reference\"\n | \"referenceType\"\n | \"referenceId\"\n | \"amount\"\n | \"mint\"\n | \"decimals\"\n | \"recipient\"\n | \"status\"\n | \"fulfillmentStatus\"\n | \"fulfillmentToken\"\n | \"fulfillmentClaimedAt\"\n | \"expiresAt\"\n | \"signature\"\n | \"slot\"\n | \"metadata\"\n | \"createdAt\"\n | \"updatedAt\",\n DBFieldAttribute\n >;\n }\n>;\n\nconst solanaPaymentSchema: SolanaPaymentSchema = {\n solanaPayment: {\n fields: {\n reference: { type: \"string\", required: true, unique: true },\n referenceType: { type: \"string\", required: true },\n referenceId: { type: \"string\", required: true, index: true },\n amount: { type: \"string\", required: true },\n mint: { type: \"string\", required: true },\n decimals: { type: \"number\", required: true },\n recipient: { type: \"string\", required: true },\n status: { type: \"string\", required: true, defaultValue: \"pending\", index: true },\n fulfillmentStatus: { type: \"string\", required: true, defaultValue: \"pending\" },\n fulfillmentToken: { type: \"string\", required: false },\n fulfillmentClaimedAt: { type: \"date\", required: false },\n expiresAt: { type: \"date\", required: true },\n signature: { type: \"string\", required: false, unique: true },\n slot: { type: \"string\", required: false },\n metadata: { type: \"string\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n} satisfies BetterAuthPluginDBSchema;\n\nexport type SolanaPaymentsPluginSchema = SolanaPaymentSchema;\nexport const solanaPaymentsPluginSchema: SolanaPaymentSchema = solanaPaymentSchema;\n\nexport function getSchema(\n options: Pick<SolanaPaymentsOptions, \"schema\">,\n): BetterAuthPluginDBSchema {\n return mergeSchema(solanaPaymentSchema, options.schema as Parameters<typeof mergeSchema>[1]);\n}\n","import { defineErrorCodes, type BetterAuthPlugin } from \"better-auth\";\n\nimport { createPayment, getPayment, verifyPayment } from \"./routes.ts\";\nimport { getSchema } from \"./schema.ts\";\nimport type { SolanaPaymentsOptions } from \"./types.ts\";\n\nimport { PACKAGE_VERSION } from \"./version.ts\";\n\nexport { PACKAGE_VERSION } from \"./version.ts\";\nexport { getSchema, solanaPaymentsPluginSchema } from \"./schema.ts\";\nexport { createSolanaPaymentStore } from \"./store.ts\";\nexport type {\n CreateSolanaPaymentInput,\n MarkPaidInput,\n MarkPaidResult,\n SolanaPaymentStore,\n SolanaPaymentStoreContext,\n} from \"./store.ts\";\nexport type { SolanaPayment, SolanaPaymentsOptions, SolanaPaymentStatus } from \"./types.ts\";\n\nconst ERROR_CODES = defineErrorCodes({\n MISSING_SESSION: \"An authenticated session is required.\",\n UNAUTHORIZED_PAYMENT: \"Payment was not found for this owner.\",\n PAYMENT_EXPIRED: \"Payment intent has expired.\",\n INVALID_PAYMENT: \"Payment is invalid.\",\n PAYMENT_MISMATCH: \"Payment did not exactly match the stored intent.\",\n PAYMENT_PROVIDER_UNAVAILABLE: \"Solana RPC could not confirm the payment; retry verification.\",\n});\n\nexport function solanaPayments(input: SolanaPaymentsOptions) {\n const normalized = input.client.payments.createRequest({\n amount: \"0\",\n recipient: input.recipient,\n reference: \"solana-payments-recipient-normalization\",\n }).recipient;\n if (!normalized) throw new Error(\"A Solana payment recipient is required.\");\n const options = {\n ...input,\n recipient: normalized,\n paymentExpirationMs: input.paymentExpirationMs ?? 30 * 60 * 1000,\n } satisfies SolanaPaymentsOptions;\n return {\n id: \"solanaPayments\",\n version: PACKAGE_VERSION,\n endpoints: {\n createPayment: createPayment(options, \"/solana-payments/create-payment\"),\n verifyPayment: verifyPayment(options, \"/solana-payments/verify-payment\"),\n getPayment: getPayment(options, \"/solana-payments/payment\"),\n },\n schema: getSchema(options),\n $ERROR_CODES: ERROR_CODES,\n } satisfies BetterAuthPlugin;\n}\n"],"mappings":";;;;;;;;AAIA,MAAM,uBAAuB;AA+C7B,SAAgB,yBAAyB,SAAwD;CAC/F,MAAM,WAAW,YAAoE;EACnF,MAAM,SAAS,QAAQ,SAAS,MAAM;EACtC,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,sDAAsD;EAEnF,IAAI,CAAC,QAAQ,gBAAgB,OAAO;GAAE,MAAM;GAAQ,IAAI;EAAO;EAC/D,IAAI,CAAC,QAAQ,uBACX,MAAM,IAAI,MAAM,2EAA2E;EAU7F,IAAI,CAAC,MAPgB,QAAQ,QAAQ,QAAwB;GAC3D,OAAO;GACP,OAAO,CACL;IAAE,OAAO;IAAkB,OAAO,QAAQ;GAAe,GACzD;IAAE,OAAO;IAAU,OAAO;GAAO,CACnC;EACF,CAAC,GACY,MAAM,IAAI,MAAM,iDAAiD;EAC9E,OAAO;GAAE,MAAM;GAAgB,IAAI,QAAQ;EAAe;CAC5D;CAEA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cAAc,SAAS,iCAAiC;GACvE,YAAY,WAAW,SAAS,0BAA0B;EAC5D;EACA,QAAQ,UAAU,OAAO;EACzB,cAAc;CAChB;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/store.ts","../src/routes.ts","../src/schema.ts","../src/index.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nimport type { SolanaPayment } from \"./types.ts\";\n\nconst SOLANA_PAYMENT_MODEL = \"solanaPayment\";\n\ntype Adapter = {\n create<T>(input: { model: string; data: Omit<T, \"id\"> }): Promise<T>;\n findOne<T>(input: { model: string; where: WhereClause }): Promise<T | null>;\n update<T>(input: { model: string; update: Partial<T>; where: WhereClause }): Promise<T | null>;\n};\ntype WhereClause = (\n | { field: string; value: string | null }\n | { field: string; operator: \"in\"; value: string[] }\n)[];\n\nexport interface SolanaPaymentStoreContext {\n adapter: Adapter;\n session?: { user?: { id: string } | null } | null;\n organizationId?: string;\n hasOrganizationPlugin?: boolean;\n}\n\nexport type CreateSolanaPaymentInput = Omit<\n SolanaPayment,\n \"id\" | \"referenceType\" | \"referenceId\" | \"status\" | \"createdAt\" | \"updatedAt\"\n>;\n\nexport interface MarkPaidInput {\n signature?: string;\n slot?: string;\n}\n\nexport interface MarkPaidResult {\n payment: SolanaPayment | null;\n transitioned: boolean;\n}\n\nexport interface SolanaPaymentStore {\n assertOwner(): Promise<void>;\n create(input: CreateSolanaPaymentInput): Promise<SolanaPayment>;\n findById(id: string): Promise<SolanaPayment | null>;\n findByReference(reference: string): Promise<SolanaPayment | null>;\n markPaid(reference: string, input?: MarkPaidInput): Promise<SolanaPayment | null>;\n markPaidWithTransition(\n reference: string,\n input?: MarkPaidInput,\n recoverExpired?: boolean,\n ): Promise<MarkPaidResult>;\n claimFulfillment(reference: string): Promise<SolanaPayment | null>;\n finishFulfillment(\n reference: string,\n token: string,\n completed: boolean,\n ): Promise<SolanaPayment | null>;\n markExpired(reference: string): Promise<SolanaPayment | null>;\n}\n\nexport function createSolanaPaymentStore(context: SolanaPaymentStoreContext): SolanaPaymentStore {\n const getOwner = async (): Promise<{ type: \"user\" | \"organization\"; id: string }> => {\n const userId = context.session?.user?.id;\n if (!userId) throw new Error(\"A session user is required to access Solana payments\");\n\n if (!context.organizationId) return { type: \"user\", id: userId };\n if (!context.hasOrganizationPlugin) {\n throw new Error(\"The Better Auth organization plugin is required for organization payments\");\n }\n\n const member = await context.adapter.findOne<{ id: string }>({\n model: \"member\",\n where: [\n { field: \"organizationId\", value: context.organizationId },\n { field: \"userId\", value: userId },\n ],\n });\n if (!member) throw new Error(\"The session user must be an organization member\");\n return { type: \"organization\", id: context.organizationId };\n };\n\n const paymentWhere = async (where: WhereClause): Promise<WhereClause> => {\n const owner = await getOwner();\n return [\n ...where,\n { field: \"referenceType\", value: owner.type },\n { field: \"referenceId\", value: owner.id },\n ];\n };\n\n const findByReference = async (reference: string): Promise<SolanaPayment | null> =>\n context.adapter.findOne<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n where: await paymentWhere([{ field: \"reference\", value: reference }]),\n });\n\n const markPaidWithTransition = async (\n reference: string,\n input: MarkPaidInput = {},\n recoverExpired = false,\n ): Promise<MarkPaidResult> => {\n const payment = await findByReference(reference);\n if (!payment) return { payment: null, transitioned: false };\n if (payment.status === \"paid\") return { payment, transitioned: false };\n if (payment.status !== \"pending\" && !(recoverExpired && payment.status === \"expired\")) {\n return { payment: null, transitioned: false };\n }\n if (input.signature) {\n const existing = await context.adapter.findOne<{ id: string }>({\n model: SOLANA_PAYMENT_MODEL,\n where: [{ field: \"signature\", value: input.signature }],\n });\n if (existing && existing.id !== payment.id) return { payment: null, transitioned: false };\n }\n const updated = await context.adapter.update<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n update: { status: \"paid\", ...input, updatedAt: new Date() },\n where: await paymentWhere([\n { field: \"id\", value: payment.id },\n recoverExpired\n ? { field: \"status\", operator: \"in\", value: [\"pending\", \"expired\"] }\n : { field: \"status\", value: \"pending\" },\n ]),\n });\n if (updated) return { payment: updated, transitioned: true };\n const current = await findByReference(reference);\n return { payment: current?.status === \"paid\" ? current : null, transitioned: false };\n };\n\n return {\n async assertOwner() {\n await getOwner();\n },\n async create(input) {\n const owner = await getOwner();\n const now = new Date();\n return context.adapter.create<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n data: {\n ...input,\n referenceType: owner.type,\n referenceId: owner.id,\n status: \"pending\",\n fulfillmentStatus: \"pending\",\n fulfillmentToken: null,\n fulfillmentClaimedAt: null,\n createdAt: now,\n updatedAt: now,\n },\n });\n },\n findById: async (id) =>\n context.adapter.findOne<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n where: await paymentWhere([{ field: \"id\", value: id }]),\n }),\n findByReference,\n async markPaid(reference, input = {}) {\n return (await markPaidWithTransition(reference, input)).payment;\n },\n markPaidWithTransition,\n async claimFulfillment(reference) {\n const payment = await findByReference(reference);\n if (\n !payment ||\n payment.status !== \"paid\" ||\n !payment.fulfillmentStatus ||\n payment.fulfillmentStatus === \"completed\"\n )\n return null;\n if (\n payment.fulfillmentStatus === \"processing\" &&\n payment.fulfillmentClaimedAt &&\n new Date(payment.fulfillmentClaimedAt).getTime() > Date.now() - 5 * 60_000\n )\n return null;\n return context.adapter.update<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n where: await paymentWhere([\n { field: \"id\", value: payment.id },\n { field: \"fulfillmentStatus\", value: payment.fulfillmentStatus },\n { field: \"fulfillmentToken\", value: payment.fulfillmentToken ?? null },\n ]),\n update: {\n fulfillmentStatus: \"processing\",\n fulfillmentToken: randomUUID(),\n fulfillmentClaimedAt: new Date(),\n updatedAt: new Date(),\n },\n });\n },\n async finishFulfillment(reference, token, completed) {\n return context.adapter.update<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n where: await paymentWhere([\n { field: \"reference\", value: reference },\n { field: \"fulfillmentToken\", value: token },\n { field: \"fulfillmentStatus\", value: \"processing\" },\n ]),\n update: {\n fulfillmentStatus: completed ? \"completed\" : \"pending\",\n fulfillmentToken: null,\n fulfillmentClaimedAt: null,\n updatedAt: new Date(),\n },\n });\n },\n async markExpired(reference) {\n const payment = await findByReference(reference);\n if (!payment || payment.status !== \"pending\")\n return payment?.status === \"expired\" ? payment : null;\n\n return context.adapter.update<SolanaPayment>({\n model: SOLANA_PAYMENT_MODEL,\n update: { status: \"expired\", updatedAt: new Date() },\n where: await paymentWhere([\n { field: \"id\", value: payment.id },\n { field: \"status\", value: \"pending\" },\n ]),\n });\n },\n };\n}\n","import { randomBytes } from \"node:crypto\";\n\nimport {\n APIError,\n createAuthEndpoint,\n getSessionFromCtx,\n originCheckMiddleware,\n sessionMiddleware,\n} from \"better-auth/api\";\nimport type { GenericEndpointContext } from \"better-auth\";\nimport { formatTokenAmount, isSolanaPaymentsError } from \"solana-payments\";\nimport { z } from \"zod\";\n\nimport { createSolanaPaymentStore } from \"./store.ts\";\nimport type { SolanaPayment, SolanaPaymentsOptions } from \"./types.ts\";\n\nconst createPaymentBody = z.object({\n amount: z.string().min(1),\n metadata: z.record(z.string(), z.unknown()).optional(),\n organizationId: z.string().min(1).optional(),\n});\nconst verifyPaymentBody = z.object({\n reference: z.string().min(1),\n /** Transaction signature lets the SDK verify a candidate before scanning recent history. */\n signature: z.string().min(1).optional(),\n organizationId: z.string().min(1).optional(),\n});\nconst getPaymentQuery = z.object({\n reference: z.string().min(1),\n organizationId: z.string().min(1).optional(),\n});\n\nfunction routeError(\n code:\n | \"MISSING_SESSION\"\n | \"UNAUTHORIZED_PAYMENT\"\n | \"PAYMENT_EXPIRED\"\n | \"INVALID_PAYMENT\"\n | \"PAYMENT_MISMATCH\"\n | \"PAYMENT_PROVIDER_UNAVAILABLE\",\n message: string,\n): never {\n const status =\n code === \"MISSING_SESSION\"\n ? \"UNAUTHORIZED\"\n : code === \"PAYMENT_PROVIDER_UNAVAILABLE\"\n ? \"INTERNAL_SERVER_ERROR\"\n : \"BAD_REQUEST\";\n throw new APIError(status, {\n code,\n message,\n });\n}\n\nfunction assertOrganizationEnabled(options: SolanaPaymentsOptions, organizationId?: string) {\n if (organizationId && options.organization?.enabled !== true) {\n routeError(\"UNAUTHORIZED_PAYMENT\", \"Organization payments are not enabled.\");\n }\n}\n\nasync function paymentStore(ctx: GenericEndpointContext, organizationId?: string) {\n const session = await getSessionFromCtx(ctx);\n if (!session) routeError(\"MISSING_SESSION\", \"An authenticated session is required.\");\n try {\n const store = createSolanaPaymentStore({\n adapter: ctx.context.adapter,\n session,\n organizationId,\n hasOrganizationPlugin:\n ctx.context.options.plugins?.some((plugin) => plugin.id === \"organization\") === true,\n });\n await store.assertOwner();\n return store;\n } catch (error) {\n routeError(\n \"UNAUTHORIZED_PAYMENT\",\n error instanceof Error ? error.message : \"Unauthorized payment.\",\n );\n }\n}\n\nasync function loadPayment(\n ctx: GenericEndpointContext,\n reference: string,\n organizationId?: string,\n) {\n const store = await paymentStore(ctx, organizationId);\n try {\n const payment = await store.findByReference(reference);\n if (!payment) routeError(\"UNAUTHORIZED_PAYMENT\", \"Payment was not found for this owner.\");\n return { store, payment };\n } catch (error) {\n if (error instanceof APIError) throw error;\n routeError(\n \"UNAUTHORIZED_PAYMENT\",\n error instanceof Error ? error.message : \"Unauthorized payment.\",\n );\n }\n}\n\nfunction asResponse(payment: SolanaPayment, paymentUrl?: string) {\n return {\n id: payment.id,\n reference: payment.reference,\n amount: payment.amount,\n mint: payment.mint,\n decimals: payment.decimals,\n recipient: payment.recipient,\n status: payment.status,\n fulfillmentStatus:\n payment.fulfillmentStatus ?? (payment.status === \"paid\" ? \"completed\" : \"pending\"),\n expiresAt: payment.expiresAt,\n signature: payment.signature ?? undefined,\n slot: payment.slot ?? undefined,\n metadata: payment.metadata\n ? (JSON.parse(payment.metadata) as Record<string, unknown>)\n : undefined,\n ...(paymentUrl ? { paymentUrl } : {}),\n };\n}\n\n// Solana Pay references are public keys (base58-encoded 32-byte values).\nfunction createReference() {\n const bytes = randomBytes(32);\n const alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\n let number = BigInt(`0x${bytes.toString(\"hex\")}`);\n let encoded = \"\";\n while (number > 0n) {\n encoded = alphabet[Number(number % 58n)] + encoded;\n number /= 58n;\n }\n for (const byte of bytes) {\n if (byte !== 0) break;\n encoded = \"1\" + encoded;\n }\n return encoded;\n}\n\nasync function fulfillPayment(\n ctx: GenericEndpointContext,\n options: SolanaPaymentsOptions,\n store: Awaited<ReturnType<typeof paymentStore>>,\n payment: SolanaPayment,\n) {\n const claimed = await store.claimFulfillment(payment.reference);\n if (!claimed) return (await store.findByReference(payment.reference)) ?? payment;\n const token = claimed.fulfillmentToken!;\n try {\n await options.onPaymentComplete?.(claimed, ctx);\n const completed = await store.finishFulfillment(claimed.reference, token, true);\n if (!completed) throw new Error(\"Fulfillment lease was lost; retry verification.\");\n return completed;\n } catch (error) {\n await store.finishFulfillment(claimed.reference, token, false);\n throw error;\n }\n}\n\nexport const createPayment = <P extends string = \"/create-payment\">(\n options: SolanaPaymentsOptions,\n path: P = \"/create-payment\" as P,\n) =>\n createAuthEndpoint(\n path,\n { method: \"POST\", body: createPaymentBody, use: [sessionMiddleware, originCheckMiddleware] },\n async (ctx) => {\n assertOrganizationEnabled(options, ctx.body.organizationId);\n const store = await paymentStore(ctx, ctx.body.organizationId);\n const reference = createReference();\n const request = options.client.payments.createRequest({\n amount: ctx.body.amount,\n recipient: options.recipient,\n reference,\n metadata: ctx.body.metadata,\n });\n const payment = await store.create({\n reference: request.reference,\n amount: request.amount.toString(),\n mint: request.mint,\n decimals: request.decimals,\n recipient: request.recipient ?? options.recipient,\n expiresAt: new Date(Date.now() + (options.paymentExpirationMs ?? 30 * 60 * 1000)),\n metadata: ctx.body.metadata ? JSON.stringify(ctx.body.metadata) : null,\n signature: null,\n slot: null,\n });\n const paymentUrl = options.client.payments.toSolanaPayUrl(request).toString();\n return ctx.json(asResponse(payment, paymentUrl));\n },\n );\n\nexport const verifyPayment = <P extends string = \"/verify-payment\">(\n options: SolanaPaymentsOptions,\n path: P = \"/verify-payment\" as P,\n) =>\n createAuthEndpoint(\n path,\n { method: \"POST\", body: verifyPaymentBody, use: [sessionMiddleware, originCheckMiddleware] },\n async (ctx) => {\n assertOrganizationEnabled(options, ctx.body.organizationId);\n const { store, payment } = await loadPayment(\n ctx,\n ctx.body.reference,\n ctx.body.organizationId,\n );\n if (payment.status === \"paid\")\n return ctx.json(asResponse(await fulfillPayment(ctx, options, store, payment)));\n if (payment.status !== \"pending\" && payment.status !== \"expired\") {\n routeError(\"INVALID_PAYMENT\", \"Payment cannot be settled.\");\n }\n\n const configuredRequest = options.client.payments.createRequest({\n amount: formatTokenAmount(payment.amount, payment.decimals),\n recipient: payment.recipient,\n reference: payment.reference,\n });\n if (\n configuredRequest.mint !== payment.mint ||\n configuredRequest.decimals !== payment.decimals\n ) {\n routeError(\"PAYMENT_MISMATCH\", \"Payment asset configuration changed.\");\n }\n\n let verified;\n try {\n verified = await options.client.payments.verify({\n reference: payment.reference,\n ...(ctx.body.signature ? { signature: ctx.body.signature } : {}),\n recipient: payment.recipient,\n amount: formatTokenAmount(payment.amount, payment.decimals),\n });\n } catch (error) {\n if (\n isSolanaPaymentsError(error) &&\n [\"RPC_ERROR\", \"RPC_TIMEOUT\", \"TRANSACTION_TIMEOUT\"].includes(error.code)\n ) {\n routeError(\n \"PAYMENT_PROVIDER_UNAVAILABLE\",\n \"Solana RPC could not confirm the payment. Retry verification with the same reference.\",\n );\n }\n routeError(\n \"PAYMENT_MISMATCH\",\n error instanceof Error ? error.message : \"Payment did not match intent.\",\n );\n }\n const expired = payment.status === \"expired\" || payment.expiresAt.getTime() <= Date.now();\n if (expired && !verified.found) {\n await store.markExpired(payment.reference);\n routeError(\"PAYMENT_EXPIRED\", \"Payment intent has expired.\");\n }\n if (\n !verified.found ||\n verified.reference !== payment.reference ||\n verified.recipient !== payment.recipient ||\n !verified.signature ||\n verified.amount?.toString() !== payment.amount\n ) {\n routeError(\"PAYMENT_MISMATCH\", \"Payment did not exactly match the stored intent.\");\n }\n if (verified.confirmationStatus !== \"finalized\") {\n routeError(\n \"PAYMENT_PROVIDER_UNAVAILABLE\",\n \"Payment is awaiting finality. Retry verification.\",\n );\n }\n if (expired) {\n const rpc = await options.client.transactions\n .retrieve({ signature: verified.signature })\n .catch(() =>\n routeError(\n \"PAYMENT_PROVIDER_UNAVAILABLE\",\n \"Could not verify the transfer time. Retry verification.\",\n ),\n );\n const transaction = rpc.transaction;\n const blockTime =\n typeof transaction === \"object\" && transaction !== null && \"blockTime\" in transaction\n ? transaction.blockTime\n : undefined;\n const seconds = typeof blockTime === \"bigint\" ? Number(blockTime) : blockTime;\n if (\n rpc.signature !== verified.signature ||\n rpc.confirmationStatus !== \"finalized\" ||\n rpc.err != null ||\n (verified.slot != null && rpc.slot !== verified.slot) ||\n typeof seconds !== \"number\" ||\n !Number.isSafeInteger(seconds) ||\n seconds < Math.floor(payment.createdAt.getTime() / 1000) ||\n seconds * 1000 >= payment.expiresAt.getTime()\n ) {\n await store.markExpired(payment.reference);\n routeError(\n \"PAYMENT_EXPIRED\",\n \"No finalized transfer was recorded within the payment window.\",\n );\n }\n }\n const { payment: paid } = await store.markPaidWithTransition(\n payment.reference,\n { signature: verified.signature, slot: verified.slot?.toString() },\n expired,\n );\n if (!paid) routeError(\"INVALID_PAYMENT\", \"Payment state could not be updated.\");\n return ctx.json(asResponse(await fulfillPayment(ctx, options, store, paid)));\n },\n );\n\nexport const getPayment = <P extends string = \"/payment\">(\n options: SolanaPaymentsOptions,\n path: P = \"/payment\" as P,\n) =>\n createAuthEndpoint(\n path,\n { method: \"GET\", query: getPaymentQuery, use: [sessionMiddleware] },\n async (ctx) => {\n assertOrganizationEnabled(options, ctx.query.organizationId);\n const { store, payment } = await loadPayment(\n ctx,\n ctx.query.reference,\n ctx.query.organizationId,\n );\n const current =\n payment.status === \"pending\" && payment.expiresAt <= new Date()\n ? await store.markExpired(payment.reference)\n : payment;\n return ctx.json(asResponse(current ?? payment));\n },\n );\n","import { mergeSchema, type BetterAuthPluginDBSchema, type DBFieldAttribute } from \"better-auth/db\";\n\nimport type { SolanaPaymentsOptions } from \"./types.ts\";\n\ntype SolanaPaymentSchema = Record<\n \"solanaPayment\",\n {\n fields: Record<\n | \"reference\"\n | \"referenceType\"\n | \"referenceId\"\n | \"amount\"\n | \"mint\"\n | \"decimals\"\n | \"recipient\"\n | \"status\"\n | \"fulfillmentStatus\"\n | \"fulfillmentToken\"\n | \"fulfillmentClaimedAt\"\n | \"expiresAt\"\n | \"signature\"\n | \"slot\"\n | \"metadata\"\n | \"createdAt\"\n | \"updatedAt\",\n DBFieldAttribute\n >;\n }\n>;\n\nconst solanaPaymentSchema: SolanaPaymentSchema = {\n solanaPayment: {\n fields: {\n reference: { type: \"string\", required: true, unique: true },\n referenceType: { type: \"string\", required: true },\n referenceId: { type: \"string\", required: true, index: true },\n amount: { type: \"string\", required: true },\n mint: { type: \"string\", required: true },\n decimals: { type: \"number\", required: true },\n recipient: { type: \"string\", required: true },\n status: { type: \"string\", required: true, defaultValue: \"pending\", index: true },\n fulfillmentStatus: { type: \"string\", required: true, defaultValue: \"pending\" },\n fulfillmentToken: { type: \"string\", required: false },\n fulfillmentClaimedAt: { type: \"date\", required: false },\n expiresAt: { type: \"date\", required: true },\n signature: { type: \"string\", required: false, unique: true },\n slot: { type: \"string\", required: false },\n metadata: { type: \"string\", required: false },\n createdAt: { type: \"date\", required: true },\n updatedAt: { type: \"date\", required: true },\n },\n },\n} satisfies BetterAuthPluginDBSchema;\n\nexport type SolanaPaymentsPluginSchema = SolanaPaymentSchema;\nexport const solanaPaymentsPluginSchema: SolanaPaymentSchema = solanaPaymentSchema;\n\nexport function getSchema(\n options: Pick<SolanaPaymentsOptions, \"schema\">,\n): BetterAuthPluginDBSchema {\n return mergeSchema(solanaPaymentSchema, options.schema as Parameters<typeof mergeSchema>[1]);\n}\n","import { defineErrorCodes, type BetterAuthPlugin } from \"better-auth\";\n\nimport { createPayment, getPayment, verifyPayment } from \"./routes.ts\";\nimport { getSchema } from \"./schema.ts\";\nimport type { SolanaPaymentsOptions } from \"./types.ts\";\n\nimport { PACKAGE_VERSION } from \"./version.ts\";\n\nexport { PACKAGE_VERSION } from \"./version.ts\";\nexport { getSchema, solanaPaymentsPluginSchema } from \"./schema.ts\";\nexport { createSolanaPaymentStore } from \"./store.ts\";\nexport type {\n CreateSolanaPaymentInput,\n MarkPaidInput,\n MarkPaidResult,\n SolanaPaymentStore,\n SolanaPaymentStoreContext,\n} from \"./store.ts\";\nexport type { SolanaPayment, SolanaPaymentsOptions, SolanaPaymentStatus } from \"./types.ts\";\n\nconst ERROR_CODES = defineErrorCodes({\n MISSING_SESSION: \"An authenticated session is required.\",\n UNAUTHORIZED_PAYMENT: \"Payment was not found for this owner.\",\n PAYMENT_EXPIRED: \"Payment intent has expired.\",\n INVALID_PAYMENT: \"Payment is invalid.\",\n PAYMENT_MISMATCH: \"Payment did not exactly match the stored intent.\",\n PAYMENT_PROVIDER_UNAVAILABLE: \"Solana RPC could not confirm the payment; retry verification.\",\n});\n\nexport function solanaPayments(input: SolanaPaymentsOptions) {\n const normalized = input.client.payments.createRequest({\n amount: \"0\",\n recipient: input.recipient,\n reference: \"solana-payments-recipient-normalization\",\n }).recipient;\n if (!normalized) throw new Error(\"A Solana payment recipient is required.\");\n const options = {\n ...input,\n recipient: normalized,\n paymentExpirationMs: input.paymentExpirationMs ?? 30 * 60 * 1000,\n } satisfies SolanaPaymentsOptions;\n return {\n id: \"solanaPayments\",\n version: PACKAGE_VERSION,\n endpoints: {\n createPayment: createPayment(options, \"/solana-payments/create-payment\"),\n verifyPayment: verifyPayment(options, \"/solana-payments/verify-payment\"),\n getPayment: getPayment(options, \"/solana-payments/payment\"),\n },\n schema: getSchema(options),\n $ERROR_CODES: ERROR_CODES,\n } satisfies BetterAuthPlugin & { version: typeof PACKAGE_VERSION };\n}\n"],"mappings":";;;;;;;;AAIA,MAAM,uBAAuB;AAsD7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,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAK;CAC1C,WAAW;EAAE,MAAM;EAAQ,UAAU;CAAK;AAC5C,EACF,EACF;AAGA,MAAa,6BAAkD;AAE/D,SAAgB,UACd,SAC0B;CAC1B,OAAO,YAAY,qBAAqB,QAAQ,MAA2C;AAC7F;;ACzCA,MAAM,cAAc,iBAAiB;CACnC,iBAAiB;CACjB,sBAAsB;CACtB,iBAAiB;CACjB,iBAAiB;CACjB,kBAAkB;CAClB,8BAA8B;AAChC,CAAC;AAED,SAAgB,eAAe,OAA8B;CAC3D,MAAM,aAAa,MAAM,OAAO,SAAS,cAAc;EACrD,QAAQ;EACR,WAAW,MAAM;EACjB,WAAW;CACb,CAAC,CAAC,CAAC;CACH,IAAI,CAAC,YAAY,MAAM,IAAI,MAAM,yCAAyC;CAC1E,MAAM,UAAU;EACd,GAAG;EACH,WAAW;EACX,qBAAqB,MAAM,uBAAuB;CACpD;CACA,OAAO;EACL,IAAI;EACJ,SAAS;EACT,WAAW;GACT,eAAe,cAAc,SAAS,iCAAiC;GACvE,eAAe,cAAc,SAAS,iCAAiC;GACvE,YAAY,WAAW,SAAS,0BAA0B;EAC5D;EACA,QAAQ,UAAU,OAAO;EACzB,cAAc;CAChB;AACF"}
@@ -0,0 +1,5 @@
1
+ // src/version.ts
2
+ const PACKAGE_VERSION = "0.5.0";
3
+ export { PACKAGE_VERSION as t };
4
+
5
+ //# sourceMappingURL=version-BXUGEOkG.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version-BXUGEOkG.mjs","names":[],"sources":["../src/version.ts"],"sourcesContent":["export const PACKAGE_VERSION = \"0.5.0\"; // x-release-please-version\n"],"mappings":";AAAA,MAAa,kBAAkB"}
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "better-auth-solana-payments",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "One-time Solana payment integration for Better Auth",
5
5
  "keywords": [
6
6
  "better-auth",
7
7
  "payments",
8
8
  "solana",
9
- "solana-pay"
9
+ "solana-pay",
10
+ "tanstack-intent"
10
11
  ],
11
12
  "homepage": "https://github.com/alexasomba/better-auth-solana-payments#readme",
12
13
  "bugs": {
@@ -20,7 +21,8 @@
20
21
  },
21
22
  "files": [
22
23
  "dist",
23
- "migrations"
24
+ "migrations",
25
+ "skills"
24
26
  ],
25
27
  "type": "module",
26
28
  "sideEffects": false,
@@ -41,21 +43,21 @@
41
43
  "access": "public"
42
44
  },
43
45
  "dependencies": {
44
- "zod": "^4.6.5"
46
+ "zod": "^4.6.7"
45
47
  },
46
48
  "devDependencies": {
47
49
  "@arethetypeswrong/cli": "^0.18.5",
48
- "@better-fetch/fetch": "1.3.2",
49
- "@types/node": "^22.20.5",
50
- "better-auth": "1.7.7",
50
+ "@better-fetch/fetch": "1.3.3",
51
+ "@types/node": "^22.20.7",
52
+ "better-auth": "1.7.28",
51
53
  "publint": "^0.3.25",
52
- "typescript": "npm:@typescript/typescript6@6.0.2",
53
- "vite": "npm:@voidzero-dev/vite-plus-core@1.1.0",
54
- "vite-plus": "1.1.0"
54
+ "typescript": "7.0.2",
55
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8001",
56
+ "vite-plus": "1.8.0"
55
57
  },
56
58
  "peerDependencies": {
57
59
  "@better-fetch/fetch": "^1.3.1",
58
- "better-auth": "^1.6.25",
60
+ "better-auth": ">=1.4.22 <2",
59
61
  "solana-payments": "^1.1.0"
60
62
  },
61
63
  "engines": {
@@ -66,9 +68,12 @@
66
68
  "dev": "vp pack --watch",
67
69
  "test": "vp test run",
68
70
  "lint": "vp lint src test",
69
- "typecheck": "tsc6 -p tsconfig.json --noEmit",
71
+ "typecheck": "tsc -p tsconfig.json --noEmit",
70
72
  "check": "vp check",
71
73
  "lint:package": "publint run --strict",
72
- "lint:types": "attw --profile esm-only --pack ."
74
+ "lint:types": "attw --profile esm-only --pack .",
75
+ "starter:export": "node scripts/export-starter.mjs",
76
+ "starter:check": "node scripts/check-starters.mjs",
77
+ "creator:pack": "node scripts/pack-creator.mjs"
73
78
  }
74
79
  }
@@ -0,0 +1,21 @@
1
+ ---
2
+ name: better-auth-solana-payments-setup
3
+ description: >-
4
+ Set up better-auth-solana-payments for one-time Solana Pay checkout. Use when installing the Better Auth server and browser plugins, configuring a read-only Solana SDK, selecting a cluster or token, enabling organization scope, or running the TanStack Start demo.
5
+ license: MIT
6
+ metadata:
7
+ library: better-auth-solana-payments
8
+ library_version: "0.5.0" # x-release-please-version
9
+ purpose: Configure a new Solana payment integration and create the first payment intent.
10
+ ---
11
+
12
+ # Set up Solana payments with Better Auth
13
+
14
+ 1. Install `better-auth-solana-payments`, `better-auth`, and `solana-payments`. Use Node.js 22+, Better Auth `>=1.4.22 <2`, and the Solana SDK `^1.1.0`.
15
+ 2. On the server, create a `createReadOnlySolanaPayments` client with your RPC URL, token, and commitment. The `SOLANA_USDT` preset uses the mainnet USDT mint. Configure a mint on the same cluster as the RPC endpoint and recipient. Set a dedicated RPC provider for production.
16
+ 3. Register `solanaPayments({ client, recipient })` in `betterAuth`, use a persistent adapter, and mount the Better Auth handler. Generate and apply the plugin schema. Existing installations missing fulfillment fields need the [fulfillment migration](../solana-payment-verification/SKILL.md).
17
+ 4. Register `solanaPaymentsClient()` from `better-auth-solana-payments/client`. Call `authClient.payment.create({ amount })` from an authenticated session. Use a decimal string in token display units. Keep the recipient and mint in server configuration.
18
+ 5. Store the returned reference with the server-owned order, expected amount, currency or mint, and customer. Show the returned `paymentUrl` as a Solana Pay link or QR code. In checkout flows with fixed prices, enforce the application's price and ownership policy before fulfillment.
19
+ 6. For organization payment intents, enable Better Auth's organization plugin and `solanaPayments({ organization: { enabled: true }, ... })`. Include the same `organizationId` on create, get, and verify. Apply any finer-grained purchasing permissions in your app.
20
+
21
+ Use the [TanStack Start demo](https://github.com/alexasomba/better-auth-solana-payments/tree/main/examples/tanstack) for a devnet wallet flow. It requires a devnet mint and recipient and uses an in-memory adapter. After checkout, follow [verification and fulfillment](../solana-payment-verification/SKILL.md).
@@ -0,0 +1,29 @@
1
+ ---
2
+ name: solana-payment-verification
3
+ description: >-
4
+ Verify or fulfill a better-auth-solana-payments intent. Use for payment.verify, wallet signatures, confirmed or finalized settlement, onPaymentComplete retries, duplicate fulfillment, schema upgrades, refunds, and wrong-cluster or wrong-mint transfers.
5
+ license: MIT
6
+ metadata:
7
+ library: better-auth-solana-payments
8
+ library_version: "0.5.0" # x-release-please-version
9
+ purpose: Confirm Solana transfers and make application fulfillment recoverable.
10
+ ---
11
+
12
+ # Verify and fulfill Solana payments
13
+
14
+ 1. After the wallet submits the transaction, call `authClient.payment.verify({ reference, signature })` using the original intent reference. The signature is optional and allows the SDK to check that candidate before scanning history. Include the intent's `organizationId` if it is organization-scoped. Use `payment.get({ reference })` with the same scope to read stored state without an RPC verification.
15
+ 2. Use the configured mint, token program, recipient, reference, and expected amount to validate the transfer. The minimum accepted commitment is `confirmed`. Choose `finalized` in the SDK when that policy is required. Keep the policy and cluster fixed for outstanding intents.
16
+ 3. On a transient RPC failure or while waiting for confirmation, retry verification with bounded backoff. A mismatch can mean the transfer is still unconfirmed or used a different asset or destination. Keep the payment pending and collect the signature, network, mint, and recipient for investigation.
17
+ 4. In `onPaymentComplete`, match the payment against the server-owned order and make side effects idempotent by reference. A conditional database claim allows one active callback. Failed callbacks can be retried through verification, and a crashed claim can be recovered after five minutes. Grant application access only after the server has confirmed the order and completed fulfillment.
18
+
19
+ ## Existing databases
20
+
21
+ Before upgrading a database that lacks fulfillment fields, add `fulfillmentStatus` (default `pending`), nullable `fulfillmentToken`, and nullable `fulfillmentClaimedAt` to `solanaPayment`. Backfill previously paid records to `completed` before enabling the upgraded handler. Use the [SQLite migration](https://github.com/alexasomba/better-auth-solana-payments/blob/main/migrations/0.2.0-sqlite.sql) for the default SQLite schema as appropriate, or generate the equivalent migration for your adapter and model names.
22
+
23
+ ## Token compatibility and refunds
24
+
25
+ Standard SPL and basic Token-2022 transfers use the server's configured token program. Transfer-fee and transfer-hook mints require extension-aware verification. An RPC on one cluster cannot verify a transfer on another cluster, even if the wallet shows the same token symbol.
26
+
27
+ Refunds are separate, authorized transfers. Keep the original paid intent, track the reviewed mint, destination, amount, network, and refund signature in your application, and reconcile the refund before retrying a submission. The plugin uses read-only RPC and has no refund endpoint.
28
+
29
+ See [the verification routes](https://github.com/alexasomba/better-auth-solana-payments/blob/main/src/routes.ts) and [Solana's verification guide](https://solana.com/docs/payments/accept-payments/verification-tools).
@@ -1 +0,0 @@
1
- {"version":3,"file":"index-DlPQtl6v.d.mts","names":["_$__types_ts0.SolanaPaymentStatus"],"sources":["../src/schema.ts","../src/types.d.ts","../src/version.ts","../src/store.ts","../src/index.ts"],"mappings":";;;;KAIK,sBAAsB;EAGvB,QAAQ,kQAkBN;;KA6BM,6BAA6B;cAC5B,4BAA4B;iBAEzB,UACd,SAAS,KAAK,mCACb;;;KCxDS;UACK;EACb;EACA;EACA;EACA;;EAEA;EACA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA,uBAAuB;EACvB,WAAW;EACX;;EAEA;EACA;EACA,WAAW;EACX,WAAW;;UAEE;EACb,QAAQ;EACR,WAAW;EACX;EACA,qBAAqB,SAAS,eAAe,SAAS,2BAA2B;EACjF;IACI;;EAEJ,SAAS,kBAAkB;;;;cClClB;;;KCMR;EACH,OAAO,GAAG;IAAS;IAAe,MAAM,KAAK;MAAa,QAAQ;EAClE,QAAQ,GAAG;IAAS;IAAe,OAAO;MAAgB,QAAQ;EAClE,OAAO,GAAG;IAAS;IAAe,QAAQ,QAAQ;IAAI,OAAO;MAAgB,QAAQ;;KAElF;EAAgB;EAAe;;UAEnB;EACf,SAAS;EACT;IAAY;MAAS;;;EACrB;EACA;;KAGU,2BAA2B,KACrC;UAIe;EACf;EACA;;UAGe;EACf,SAAS;EACT;;UAGe;EACf,eAAe;EACf,OAAO,OAAO,2BAA2B,QAAQ;EACjD,SAAS,aAAa,QAAQ;EAC9B,gBAAgB,oBAAoB,QAAQ;EAC5C,SAAS,mBAAmB,QAAQ,gBAAgB,QAAQ;EAC5D,uBAAuB,mBAAmB,QAAQ,gBAAgB,QAAQ;EAC1E,iBAAiB,oBAAoB,QAAQ;EAC7C,kBACE,mBACA,eACA,qBACC,QAAQ;EACX,YAAY,oBAAoB,QAAQ;;iBAG1B,yBAAyB,SAAS,4BAA4B;;;iBCtB9D,eAAe,OAAO;;;;;;;;;;;;;;;;;;;;YAwBitD;YAA6C;;;;;;;;;YAAyN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAAtQ;YAA6C;;;;;;;;;YAAyN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAAtQ;YAA6C;;;;;;;;;YAAyN"}
@@ -1,6 +0,0 @@
1
- //#region src/version.ts
2
- const PACKAGE_VERSION = "0.4.0";
3
- //#endregion
4
- export { PACKAGE_VERSION as t };
5
-
6
- //# sourceMappingURL=version-B5dtK-2_.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"version-B5dtK-2_.mjs","names":[],"sources":["../src/version.ts"],"sourcesContent":["export const PACKAGE_VERSION = \"0.4.0\"; // x-release-please-version\n"],"mappings":";AAAA,MAAa,kBAAkB"}