@revibase/lite 0.0.42 → 0.0.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,35 +1,36 @@
1
1
  # @revibase/lite
2
2
 
3
- Add **Revibase** (a passkey-based Solana wallet) to your app. Users sign in and approve transactions in a popup, while your backend authorizes requests with a private key that stays server-side.
4
-
5
- ## Quick Start
3
+ Passkey Solana wallet: sign in and approve transactions in a popup. Backend authorizes with a server-side private key.
6
4
 
7
5
  ```bash
8
6
  pnpm add @revibase/lite
9
7
  ```
10
8
 
11
- ### 1) Get your keys
9
+ **API** — Frontend: `RevibaseProvider`, `signIn`, `transferTokens`, `executeTransaction`. Backend: `processClientAuthCallback`. Types: `UserInfo`, `ChannelStatus`, `AuthorizationFlowOptions`, `RevibaseProviderOptions`. Errors: `RevibaseError` + subclasses (`.code`). [AGENTS.md](./AGENTS.md) for automation.
12
10
 
13
- You can generate your public and private key at [https://developers.revibase.com](https://developers.revibase.com). The **clientJwk** in the config below is your public key.
11
+ ---
14
12
 
15
- ### 2) Add well-known config
13
+ ## Get started
16
14
 
17
- Create `/.well-known/revibase.json` (for example in `public/.well-known/revibase.json`):
15
+ Three steps: keys, backend route, provider.
18
16
 
19
- ```json
20
- {
21
- "clientJwk": "<public-key-from-developers.revibase.com>",
22
- "title": "My App",
23
- "description": "Connect with passkeys"
24
- }
25
- ```
17
+ ### 1. Keys
18
+
19
+ Get keys at [developers.revibase.com](https://developers.revibase.com). Add `/.well-known/revibase.json` with `clientJwk`, `title`, `description`.
26
20
 
27
- ### 3) Add backend route
21
+ ### 2. Backend
28
22
 
29
- Set `PRIVATE_KEY` to your matching private key, then forward the client payload to `processClientAuthCallback`:
23
+ Expose **POST** at **`/api/clientAuthorization`** (default). Keep `PRIVATE_KEY` server-only; HTTPS in production.
24
+
25
+ Example handler:
30
26
 
31
27
  ```ts
32
- import { processClientAuthCallback } from "@revibase/lite";
28
+ import {
29
+ processClientAuthCallback,
30
+ type DeviceSignature,
31
+ type StartMessageRequest,
32
+ type StartTransactionRequest,
33
+ } from "@revibase/lite";
33
34
 
34
35
  export async function POST(req: Request) {
35
36
  try {
@@ -45,174 +46,120 @@ export async function POST(req: Request) {
45
46
  device,
46
47
  channelId,
47
48
  });
48
- return new Response(JSON.stringify(result));
49
- } catch (error) {
50
- return new Response(
51
- JSON.stringify({
52
- error: error instanceof Error ? error.message : String(error),
53
- }),
54
- { status: 500 },
55
- );
49
+ return Response.json(result);
50
+ } catch (e) {
51
+ const msg = e instanceof Error ? e.message : String(e);
52
+ return Response.json({ error: msg }, { status: 500 });
56
53
  }
57
54
  }
58
55
  ```
59
56
 
60
- ### 4) Use in frontend
57
+ ### 3. Frontend
61
58
 
62
- If your backend route is `/api/clientAuthorization`, the default provider is enough:
59
+ Create a provider. For `executeTransaction`, pass `rpcEndpoint` in options:
63
60
 
64
61
  ```ts
65
- import { RevibaseProvider, signIn, transferTokens } from "@revibase/lite";
62
+ import {
63
+ RevibaseProvider,
64
+ signIn,
65
+ transferTokens,
66
+ executeTransaction,
67
+ } from "@revibase/lite";
66
68
 
67
69
  const provider = new RevibaseProvider();
68
70
  const { user } = await signIn(provider);
69
71
  const { txSig } = await transferTokens(provider, {
70
72
  amount: BigInt(100_000_000),
71
- destination: "RECIPIENT_ADDRESS",
72
- signer: user,
73
+ destination: "ADDRESS",
74
+ signer: user, // optional for transfers
73
75
  });
74
76
  ```
75
77
 
76
- ### 5) Optional: custom callback route
77
-
78
- If your route path is different, pass a custom callback and forward `signal`:
78
+ **Custom instructions** — Build instructions with `gill` (Solana instruction builder) or similar, then pass to `executeTransaction`.
79
79
 
80
80
  ```ts
81
- import type { ClientAuthorizationCallback } from "@revibase/lite";
82
- import { RevibaseProvider } from "@revibase/lite";
83
-
84
- const onClientAuthorizationCallback: ClientAuthorizationCallback = async (
85
- request,
86
- signal,
87
- device,
88
- channelId,
89
- ) => {
90
- const res = await fetch("/api/revibase/authorize", {
91
- method: "POST",
92
- headers: { "Content-Type": "application/json" },
93
- body: JSON.stringify({ request, device, channelId }),
94
- signal,
95
- });
96
- const data = await res.json();
97
- if (!res.ok) throw new Error(data?.error ?? "Authorization failed");
98
- return data;
99
- };
100
-
101
- const provider = new RevibaseProvider(onClientAuthorizationCallback);
102
- ```
81
+ import { RevibaseProvider, signIn, executeTransaction } from "@revibase/lite";
82
+ import { address, createNoopSigner } from "gill";
83
+ import { getTransferSolInstruction } from "gill/programs";
103
84
 
104
- ### 6) Optional: device binding
85
+ const provider = new RevibaseProvider({
86
+ rpcEndpoint: "https://api.mainnet-beta.solana.com",
87
+ });
88
+ const { user } = await signIn(provider);
105
89
 
106
- ```ts
107
- const { channelId, url } = await provider.createChannel();
108
- // Open `url` in a new tab so the user can complete the channel handshake
109
- // Pass channelId to use the channel (no popup) for subsequent flows:
110
- const { user } = await signIn(provider, channelId);
111
- const { txSig } = await transferTokens(provider, { amount: BigInt(100_000_000), destination: "RECIPIENT_ADDRESS", signer: user }, channelId);
112
- // When done, close the channel:
113
- await provider.closeChannel(channelId);
114
- // Or close all channels: await provider.closeAllChannels();
90
+ const { txSig } = await executeTransaction(provider, {
91
+ instructions: [
92
+ getTransferSolInstruction({
93
+ source: createNoopSigner(address(user.walletAddress)),
94
+ destination: address("RECIPIENT_WALLET_ADDRESS"),
95
+ amount: 1_000_000n,
96
+ }),
97
+ ],
98
+ signer: user,
99
+ });
115
100
  ```
116
101
 
117
- ## How it works
118
-
119
- 1. **Frontend** opens Revibase popup and sends auth payload to your backend callback.
120
- 2. **Backend** calls `processClientAuthCallback` with `request`, `privateKey`, and `req.signal`.
121
- 3. **Frontend** receives `{ user }` or `{ txSig, user }`.
122
-
123
- Your private key is server-only. The browser only handles payloads and results.
124
-
125
- For custom instructions, use `executeTransaction` (see API reference).
102
+ Default: auth in popup. For auth on another device, use a channel (below).
126
103
 
127
104
  ---
128
105
 
129
- **Quick checklist**
130
-
131
- - Install `@revibase/lite`.
132
- - Add `/.well-known/revibase.json` with `clientJwk`.
133
- - Set `PRIVATE_KEY` on the server.
134
- - Add a POST route using `processClientAuthCallback` and pass `req.signal`.
135
- - Create `RevibaseProvider` and ensure callback `fetch` uses `signal`.
136
- - Call `signIn(provider)` and/or `transferTokens` / `executeTransaction`. For device binding, pass `channelId` as the last argument and use `closeChannel(channelId)` or `closeAllChannels()` when done.
137
-
138
- **Security note:** Keep `PRIVATE_KEY` server-only and use HTTPS in production.
139
-
140
- ---
106
+ ## Auth on another device (channel)
141
107
 
142
- ## API Reference
108
+ Channel: auth on another device; requests go there. `createChannel()` → open `url` on that device:
143
109
 
144
- `@revibase/lite` exports browser client helpers, the browser `RevibaseProvider`, server helpers, and shared types.
145
-
146
- ### Client (browser)
147
-
148
- | Function | Description |
149
- | ---------------------------------------- | --------------------------------------------------------------------------------------- |
150
- | **`signIn(provider, channelId?)`** | Opens the auth popup (or uses channel when `channelId` is set) and returns `{ user: UserInfo }` after passkey auth. |
151
- | **`executeTransaction(provider, args, channelId?)`** | Builds and executes a custom transaction. Action type is selected from wallet settings. Pass `channelId` for device-bound flow. |
152
- | **`transferTokens(provider, args, channelId?)`** | Transfers SOL or SPL tokens. Set `mint` for SPL; omit for native SOL. `amount` must be &gt; 0; `destination` is required. Pass `channelId` for device-bound flow. |
153
-
154
- **Signatures**
110
+ ```ts
111
+ const { channelId, url } = await provider.createChannel();
112
+ ```
155
113
 
156
114
  ```ts
157
- function signIn(
158
- provider: RevibaseProvider,
159
- channelId?: string,
160
- ): Promise<{ user: UserInfo }>;
161
-
162
- function executeTransaction(
163
- provider: RevibaseProvider,
164
- args: {
165
- instructions: Instruction[];
166
- signer: UserInfo;
167
- hasTxManager?: boolean;
168
- additionalSigners?: AdditionalSignersParam;
169
- addressesByLookupTableAddress?: AddressesByLookupTableAddress;
170
- },
171
- channelId?: string,
172
- ): Promise<{ txSig?: string; user: UserInfo }>;
173
-
174
- function transferTokens(
175
- provider: RevibaseProvider,
176
- args: {
177
- amount: number | bigint;
178
- destination: string;
179
- signer?: UserInfo;
180
- mint?: string;
181
- tokenProgram?: string;
182
- },
183
- channelId?: string,
184
- ): Promise<{ txSig?: string; user: UserInfo }>;
115
+ const { user } = await signIn(provider, { channelId });
116
+ const { txSig } = await transferTokens(
117
+ provider,
118
+ { amount, destination, signer: user },
119
+ { channelId },
120
+ );
121
+ // Or: executeTransaction(provider, { instructions, signer: user }, { channelId })
185
122
  ```
186
123
 
187
- ### Provider (browser)
124
+ Use `subscribeToChannelStatus` to check channel status.
188
125
 
189
- **`RevibaseProvider`** — Connects your app to the Revibase auth popup and your backend route.
126
+ ```ts
127
+ import { ChannelStatus } from "@revibase/lite";
128
+
129
+ provider.subscribeToChannelStatus((id, entry) => {
130
+ switch (entry.status) {
131
+ case ChannelStatus.AUTHENTICATING:
132
+ break; // show "Connecting…"
133
+ case ChannelStatus.AWAITING_RECIPIENT:
134
+ break; // show "Waiting for other device"
135
+ case ChannelStatus.RECIPIENT_CONNECTED:
136
+ break; // show "Connected" (entry.recipient)
137
+ case ChannelStatus.RECIPIENT_DISCONNECTED:
138
+ break; // show "Other device left"
139
+ case ChannelStatus.AUTO_RECONNECTING:
140
+ break; // show "Reconnecting…" (entry.reconnectAttempt)
141
+ case ChannelStatus.CONNECTION_LOST:
142
+ break; // show "Connection lost. [Retry]" → provider.reconnectChannel(id)
143
+ case ChannelStatus.CHANNEL_CLOSED:
144
+ break; // show "Channel closed"
145
+ case ChannelStatus.ERROR:
146
+ break; // show entry.error
147
+ }
148
+ });
149
+ ```
190
150
 
191
- - **Constructor:** `new RevibaseProvider(onClientAuthorizationCallback?, providerOrigin?)`
192
- - `onClientAuthorizationCallback` — Optional. Called with `(request, signal, device, channelId)`. POST `request`, `device`, and `channelId` to your backend and return JSON. Pass `signal` to `fetch` for cancellation.
193
- - `providerOrigin` — Optional. Default `https://auth.revibase.com`.
194
- - **Methods**
195
- - `createChannel(): Promise<{ channelId: string; url: string }>` — Creates a channel and enables device-bound flows. Open the returned `url` in a new tab so the user can complete the handshake. Pass `channelId` to `signIn`, `transferTokens`, or `executeTransaction` to use the channel (no popup). Callback payloads will include device proof (`device`) and `channelId`.
196
- - `closeChannel(channelId: string): Promise<void>` — Closes the given channel on the provider and removes it from the local list.
197
- - `getAllChannelIds(): string[]` — Returns all active channel IDs.
198
- - `closeAllChannels(): Promise<void>` — Closes all active channels.
151
+ ### Reconnect
199
152
 
200
- ### Server
153
+ If the channel connection is lost, call `reconnectChannel(channelId)`:
201
154
 
202
- | Function | Description |
203
- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
204
- | **`processClientAuthCallback(options)`** | Validates the start request, calls Revibase start + getResult APIs, and returns `{ user }` (message) or `{ txSig, user }` (transaction). Pass `req.signal` to cancel fetches when the client disconnects. |
155
+ ```ts
156
+ provider.reconnectChannel(channelId);
157
+ ```
205
158
 
206
- **Signatures**
159
+ ### Cleanup
207
160
 
208
161
  ```ts
209
- function processClientAuthCallback(options: {
210
- request: StartMessageRequest | StartTransactionRequest;
211
- signal: AbortSignal; // pass req.signal from your POST route
212
- privateKey: string; // base64-encoded JWK
213
- device?: DeviceSignature; // { jwk, jws } from device-bound key when channelId is used
214
- channelId?: string;
215
- providerOrigin?: string;
216
- rpId?: string;
217
- }): Promise<{ txSig?: string; user: UserInfo }>;
162
+ provider.closeChannel(channelId);
163
+ // or
164
+ provider.closeAllChannels();
218
165
  ```
package/dist/index.cjs CHANGED
@@ -1,10 +1,9 @@
1
- 'use strict';var core=require('@revibase/core'),jose=require('jose'),co=require('zod'),server=require('@simplewebauthn/server');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var co__default=/*#__PURE__*/_interopDefault(co);var De=1,ge=2,Ne=3,Ce=4,Oe=5,Se=6,fe=7,me=8,pe=9,Me=10,he=-32700,ye=-32603,Le=-32602,Ue=-32601,ve=-32600,Pe=-32019,Fe=-32018,be=-32017,Be=-32016,ze=-32015,we=-32014,ke=-32013,xe=-32012,We=-32011,Ge=-32010,Ve=-32009,He=-32008,Ke=-32007,$e=-32006,Ye=-32005,Xe=-32004,Ze=-32003,qe=-32002,je=-32001,h=28e5,y=2800001,Je=2800002,w=2800003,k=2800004,x=2800005,W=2800006,G=2800007,V=2800008,H=2800009,K=2800010,$=2800011,Qe=323e4,et=32300001,tt=3230002,nt=3230003,rt=3230004,it=361e4,ot=3610001,at=3610002,st=3610003,ct=3610004,dt=3610005,ut=3610006,It=3610007,_t=3611e3,At=3704e3,Et=3704001,Rt=3704002,Tt=3704003,lt=3704004,Dt=4128e3,gt=4128001,Nt=4128002,Ct=4615e3,Ot=4615001,St=4615002,ft=4615003,mt=4615004,pt=4615005,Mt=4615006,ht=4615007,yt=4615008,Lt=4615009,Ut=4615010,vt=4615011,Pt=4615012,Ft=4615013,bt=4615014,Bt=4615015,zt=4615016,wt=4615017,kt=4615018,xt=4615019,Wt=4615020,Gt=4615021,Vt=4615022,Ht=4615023,Kt=4615024,$t=4615025,Yt=4615026,Xt=4615027,Zt=4615028,qt=4615029,jt=4615030,Jt=4615031,Qt=4615032,en=4615033,tn=4615034,nn=4615035,rn=4615036,on=4615037,an=4615038,sn=4615039,cn=4615040,dn=4615041,un=4615042,In=4615043,_n=4615044,An=4615045,En=4615046,Rn=4615047,Tn=4615048,ln=4615049,Dn=4615050,gn=4615051,Nn=4615052,Cn=4615053,On=4615054,Sn=5508e3,fn=5508001,mn=5508002,pn=5508003,Mn=5508004,hn=5508005,yn=5508006,Ln=5508007,Un=5508008,vn=5508009,Pn=5508010,Fn=5508011,bn=5663e3,Bn=5663001,zn=5663002,wn=5663003,kn=5663004,xn=5663005,Wn=5663006,Gn=5663007,Vn=5663008,Hn=5663009,Kn=5663010,$n=5663011,Yn=5663012,Xn=5663013,Zn=5663014,qn=5663015,jn=5663016,Jn=5663017,Qn=5663018,er=5663019,tr=5663020,nr=5663021,rr=5663022,ir=705e4,or=7050001,ar=7050002,sr=7050003,cr=7050004,dr=7050005,ur=7050006,Ir=7050007,_r=7050008,Ar=7050009,Er=7050010,Rr=7050011,Tr=7050012,lr=7050013,Dr=7050014,gr=7050015,Nr=7050016,Cr=7050017,Or=7050018,Sr=7050019,fr=7050020,mr=7050021,pr=7050022,Mr=7050023,hr=7050024,yr=7050025,Lr=7050026,Ur=7050027,vr=7050028,Pr=7050029,Fr=7050030,br=7050031,Br=7050032,zr=7050033,wr=7050034,kr=7050035,xr=7050036,Wr=7618e3,Gr=7618001,Vr=7618002,Hr=7618003,Kr=8078e3,$r=8078001,Yr=8078002,Xr=8078003,Zr=8078004,qr=8078005,jr=8078006,Jr=8078007,Qr=8078008,ei=8078009,ti=8078010,L=8078011,U=8078012,ni=8078013,ri=8078014,ii=8078015,oi=8078016,ai=8078017,si=8078018,ci=8078019,di=8078020,ui=8078021,Ii=8078022,_i=8078023,Ai=81e5,Ei=8100001,Ri=8100002,Ti=8100003,li=819e4,Di=8190001,gi=8190002,Ni=8190003,Ci=8190004,Oi=99e5,Si=9900001,fi=9900002,mi=9900003,pi=9900004,Mi=9900005,hi=9900006;function Y(t){return Array.isArray(t)?"%5B"+t.map(Y).join("%2C%20")+"%5D":typeof t=="bigint"?`${t}n`:encodeURIComponent(String(t!=null&&Object.getPrototypeOf(t)===null?{...t}:t))}function yi([t,e]){return `${t}=${Y(e)}`}function Li(t){let e=Object.entries(t).map(yi).join("&");return Buffer.from(e,"utf8").toString("base64")}var Ui={[Qe]:"Account not found at address: $address",[rt]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[nt]:"Expected decoded account at address: $address",[tt]:"Failed to decode account data at address: $address",[et]:"Accounts not found at addresses: $addresses",[H]:"Unable to find a viable program address bump seed.",[Je]:"$putativeAddress is not a base58-encoded address.",[h]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[w]:"The `CryptoKey` must be an `Ed25519` public key.",[$]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[V]:"Invalid seeds; point must fall off the Ed25519 curve.",[k]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[W]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[G]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[x]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[K]:"Program address cannot end with PDA marker.",[y]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[Ce]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[De]:"The network has progressed past the last block for which this transaction could have been committed.",[Kr]:"Codec [$codecDescription] cannot decode empty byte arrays.",[Ii]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[di]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[qr]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[jr]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Zr]:"Encoder and decoder must either both be fixed-size or variable-size.",[Qr]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Yr]:"Expected a fixed-size codec, got a variable-size one.",[ni]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Xr]:"Expected a variable-size codec, got a fixed-size one.",[ci]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[$r]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[si]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[ei]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[ti]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[ii]:"Invalid literal union variant. Expected one of [$variants], got $value.",[Jr]:"Expected [$codecDescription] to have $expected items, got $actual.",[U]:"Invalid value $value for base $base with alphabet $alphabet.",[oi]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[L]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[ri]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[ui]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[ai]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[_i]:"This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",[_t]:"No random values implementation could be found.",[Lt]:"instruction requires an uninitialized account",[Ht]:"instruction tries to borrow reference for an account which is already borrowed",[Kt]:"instruction left account with an outstanding borrowed reference",[Gt]:"program other than the account's owner changed the size of the account data",[pt]:"account data too small for instruction",[Vt]:"instruction expected an executable account",[En]:"An account does not have enough lamports to be rent-exempt",[Tn]:"Program arithmetic overflowed",[An]:"Failed to serialize or deserialize account data: $encodedData",[On]:"Builtin programs must consume compute units",[Qt]:"Cross-program invocation call depth too deep",[an]:"Computational budget exceeded",[Yt]:"custom program error: #$code",[wt]:"instruction contains duplicate accounts",[$t]:"instruction modifications of multiply-passed account differ",[jt]:"executable accounts must be rent exempt",[Zt]:"instruction changed executable accounts data",[qt]:"instruction changed the balance of an executable account",[kt]:"instruction changed executable bit of an account",[bt]:"instruction modified data of an account it does not own",[Ft]:"instruction spent from the balance of an account it does not own",[Ot]:"generic instruction error",[Dn]:"Provided owner is not allowed",[In]:"Account is immutable",[_n]:"Incorrect authority provided",[ht]:"incorrect program id for instruction",[Mt]:"insufficient funds for instruction",[mt]:"invalid account data for instruction",[Rn]:"Invalid account owner",[St]:"invalid program argument",[Xt]:"program returned invalid error code",[ft]:"invalid instruction data",[on]:"Failed to reallocate account data",[rn]:"Provided seeds do not result in a valid address",[gn]:"Accounts data allocations exceeded the maximum allowed per transaction",[Nn]:"Max accounts exceeded",[Cn]:"Max instruction trace length exceeded",[nn]:"Length of the seed is too long for address generation",[en]:"An account required by the instruction is missing",[yt]:"missing required signature for instruction",[Pt]:"instruction illegally modified the program id of an account",[Wt]:"insufficient account keys for instruction",[sn]:"Cross-program invocation with unauthorized signer or writable account",[cn]:"Failed to create program execution environment",[un]:"Program failed to compile",[dn]:"Program failed to complete",[zt]:"instruction modified data of a read-only account",[Bt]:"instruction changed the balance of a read-only account",[tn]:"Cross-program invocation reentrancy not allowed for this instruction",[xt]:"instruction modified rent epoch of an account",[vt]:"sum of account balances before and after instruction do not match",[Ut]:"instruction requires an initialized account",[Ct]:"",[Jt]:"Unsupported program id",[ln]:"Unsupported sysvar",[Mi]:"Invalid instruction plan kind: $kind.",[Vr]:"The provided instruction plan is empty.",[Hr]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute and the `cause` error for more details.",[Wr]:"The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",[hi]:"Invalid transaction plan kind: $kind.",[Gr]:"No more instructions to pack; the message packer has completed the instruction plan.",[Dt]:"The instruction does not have any accounts.",[gt]:"The instruction does not have any data.",[Nt]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[Oe]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[ge]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[fi]:"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[pi]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[Si]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Oi]:"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[mi]:"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[ye]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Le]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[ve]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Ue]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[he]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[xe]:"$__serverMessage",[je]:"$__serverMessage",[Xe]:"$__serverMessage",[we]:"$__serverMessage",[be]:"Epoch rewards period still active at slot $slot",[Ge]:"$__serverMessage",[Ve]:"$__serverMessage",[Pe]:"Failed to query long-term storage; please try again",[Be]:"Minimum context slot has not been reached",[Ye]:"Node is unhealthy; behind by $numSlotsBehind slots",[He]:"No snapshot",[qe]:"Transaction simulation failed",[Fe]:"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",[Ke]:"$__serverMessage",[We]:"Transaction history is not available from this node",[$e]:"$__serverMessage",[ke]:"Transaction signature length mismatch",[Ze]:"Transaction signature verification failure",[ze]:"$__serverMessage",[At]:"Key pair bytes must be of length 64, got $byteLength.",[Et]:"Expected private key bytes with length 32. Actual length: $actualLength.",[Rt]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[lt]:"The provided private key does not match the provided public key.",[Tt]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[Se]:"Lamports value must be in the range [0, 2e64-1]",[fe]:"`$value` cannot be parsed as a `BigInt`",[Me]:"$message",[me]:"`$value` cannot be parsed as a `Number`",[Ne]:"No nonce account could be found at address `$nonceAccountAddress`",[li]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[gi]:"WebSocket was closed before payload could be added to the send buffer",[Ni]:"WebSocket connection closed",[Ci]:"WebSocket failed to connect",[Di]:"Failed to obtain a subscription id from the server",[Ti]:"Could not find an API plan for RPC method: `$method`",[Ai]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[Ri]:"HTTP error ($statusCode): $message",[Ei]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Sn]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[fn]:"The provided value does not implement the `KeyPairSigner` interface",[pn]:"The provided value does not implement the `MessageModifyingSigner` interface",[Mn]:"The provided value does not implement the `MessagePartialSigner` interface",[mn]:"The provided value does not implement any of the `MessageSigner` interfaces",[yn]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Ln]:"The provided value does not implement the `TransactionPartialSigner` interface",[Un]:"The provided value does not implement the `TransactionSendingSigner` interface",[hn]:"The provided value does not implement any of the `TransactionSigner` interfaces",[vn]:"More than one `TransactionSendingSigner` was identified.",[Pn]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Fn]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[It]:"Cannot export a non-extractable key.",[ot]:"No digest implementation could be found.",[it]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[at]:`This runtime does not support the generation of Ed25519 key pairs.
1
+ 'use strict';var core=require('@revibase/core'),jose=require('jose'),_a=require('zod'),server=require('@simplewebauthn/server');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var _a__default=/*#__PURE__*/_interopDefault(_a);var ot=1,it=2,at=3,st=4,ct=5,dt=6,ut=7,It=8,_t=9,At=10,Et=-32700,lt=-32603,Rt=-32602,Tt=-32601,Dt=-32600,gt=-32019,Nt=-32018,Ct=-32017,St=-32016,Ot=-32015,ft=-32014,mt=-32013,pt=-32012,ht=-32011,Mt=-32010,yt=-32009,Lt=-32008,Ut=-32007,vt=-32006,bt=-32005,Pt=-32004,Ft=-32003,Bt=-32002,zt=-32001,oe=28e5,ie=2800001,wt=2800002,Te=2800003,De=2800004,ge=2800005,Ne=2800006,Ce=2800007,Se=2800008,Oe=2800009,fe=2800010,me=2800011,kt=323e4,Wt=32300001,xt=3230002,Gt=3230003,Ht=3230004,Vt=361e4,Kt=3610001,$t=3610002,Yt=3610003,Xt=3610004,Zt=3610005,qt=3610006,jt=3610007,Jt=3611e3,Qt=3704e3,en=3704001,tn=3704002,nn=3704003,rn=3704004,on=4128e3,an=4128001,sn=4128002,cn=4615e3,dn=4615001,un=4615002,In=4615003,_n=4615004,An=4615005,En=4615006,ln=4615007,Rn=4615008,Tn=4615009,Dn=4615010,gn=4615011,Nn=4615012,Cn=4615013,Sn=4615014,On=4615015,fn=4615016,mn=4615017,pn=4615018,hn=4615019,Mn=4615020,yn=4615021,Ln=4615022,Un=4615023,vn=4615024,bn=4615025,Pn=4615026,Fn=4615027,Bn=4615028,zn=4615029,wn=4615030,kn=4615031,Wn=4615032,xn=4615033,Gn=4615034,Hn=4615035,Vn=4615036,Kn=4615037,$n=4615038,Yn=4615039,Xn=4615040,Zn=4615041,qn=4615042,jn=4615043,Jn=4615044,Qn=4615045,er=4615046,tr=4615047,nr=4615048,rr=4615049,or=4615050,ir=4615051,ar=4615052,sr=4615053,cr=4615054,dr=5508e3,ur=5508001,Ir=5508002,_r=5508003,Ar=5508004,Er=5508005,lr=5508006,Rr=5508007,Tr=5508008,Dr=5508009,gr=5508010,Nr=5508011,Cr=5663e3,Sr=5663001,Or=5663002,fr=5663003,mr=5663004,pr=5663005,hr=5663006,Mr=5663007,yr=5663008,Lr=5663009,Ur=5663010,vr=5663011,br=5663012,Pr=5663013,Fr=5663014,Br=5663015,zr=5663016,wr=5663017,kr=5663018,Wr=5663019,xr=5663020,Gr=5663021,Hr=5663022,Vr=705e4,Kr=7050001,$r=7050002,Yr=7050003,Xr=7050004,Zr=7050005,qr=7050006,jr=7050007,Jr=7050008,Qr=7050009,eo=7050010,to=7050011,no=7050012,ro=7050013,oo=7050014,io=7050015,ao=7050016,so=7050017,co=7050018,uo=7050019,Io=7050020,_o=7050021,Ao=7050022,Eo=7050023,lo=7050024,Ro=7050025,To=7050026,Do=7050027,go=7050028,No=7050029,Co=7050030,So=7050031,Oo=7050032,fo=7050033,mo=7050034,po=7050035,ho=7050036,Mo=7618e3,yo=7618001,Lo=7618002,Uo=7618003,vo=8078e3,bo=8078001,Po=8078002,Fo=8078003,Bo=8078004,zo=8078005,wo=8078006,ko=8078007,Wo=8078008,xo=8078009,Go=8078010,ae=8078011,se=8078012,Ho=8078013,Vo=8078014,Ko=8078015,$o=8078016,Yo=8078017,Xo=8078018,Zo=8078019,qo=8078020,jo=8078021,Jo=8078022,Qo=8078023,ei=81e5,ti=8100001,ni=8100002,ri=8100003,oi=819e4,ii=8190001,ai=8190002,si=8190003,ci=8190004,di=99e5,ui=9900001,Ii=9900002,_i=9900003,Ai=9900004,Ei=9900005,li=9900006;function pe(t){return Array.isArray(t)?"%5B"+t.map(pe).join("%2C%20")+"%5D":typeof t=="bigint"?`${t}n`:encodeURIComponent(String(t!=null&&Object.getPrototypeOf(t)===null?{...t}:t))}function Ri([t,e]){return `${t}=${pe(e)}`}function Ti(t){let e=Object.entries(t).map(Ri).join("&");return Buffer.from(e,"utf8").toString("base64")}var Di={[kt]:"Account not found at address: $address",[Ht]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[Gt]:"Expected decoded account at address: $address",[xt]:"Failed to decode account data at address: $address",[Wt]:"Accounts not found at addresses: $addresses",[Oe]:"Unable to find a viable program address bump seed.",[wt]:"$putativeAddress is not a base58-encoded address.",[oe]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Te]:"The `CryptoKey` must be an `Ed25519` public key.",[me]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Se]:"Invalid seeds; point must fall off the Ed25519 curve.",[De]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[Ne]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[Ce]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[ge]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[fe]:"Program address cannot end with PDA marker.",[ie]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[st]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[ot]:"The network has progressed past the last block for which this transaction could have been committed.",[vo]:"Codec [$codecDescription] cannot decode empty byte arrays.",[Jo]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[qo]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[zo]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[wo]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Bo]:"Encoder and decoder must either both be fixed-size or variable-size.",[Wo]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[Po]:"Expected a fixed-size codec, got a variable-size one.",[Ho]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Fo]:"Expected a variable-size codec, got a fixed-size one.",[Zo]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[bo]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[Xo]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[xo]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Go]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Ko]:"Invalid literal union variant. Expected one of [$variants], got $value.",[ko]:"Expected [$codecDescription] to have $expected items, got $actual.",[se]:"Invalid value $value for base $base with alphabet $alphabet.",[$o]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[ae]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Vo]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[jo]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[Yo]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[Qo]:"This decoder expected a byte array of exactly $expectedLength bytes, but $numExcessBytes unexpected excess bytes remained after decoding. Are you sure that you have chosen the correct decoder for this data?",[Jt]:"No random values implementation could be found.",[Tn]:"instruction requires an uninitialized account",[Un]:"instruction tries to borrow reference for an account which is already borrowed",[vn]:"instruction left account with an outstanding borrowed reference",[yn]:"program other than the account's owner changed the size of the account data",[An]:"account data too small for instruction",[Ln]:"instruction expected an executable account",[er]:"An account does not have enough lamports to be rent-exempt",[nr]:"Program arithmetic overflowed",[Qn]:"Failed to serialize or deserialize account data: $encodedData",[cr]:"Builtin programs must consume compute units",[Wn]:"Cross-program invocation call depth too deep",[$n]:"Computational budget exceeded",[Pn]:"custom program error: #$code",[mn]:"instruction contains duplicate accounts",[bn]:"instruction modifications of multiply-passed account differ",[wn]:"executable accounts must be rent exempt",[Bn]:"instruction changed executable accounts data",[zn]:"instruction changed the balance of an executable account",[pn]:"instruction changed executable bit of an account",[Sn]:"instruction modified data of an account it does not own",[Cn]:"instruction spent from the balance of an account it does not own",[dn]:"generic instruction error",[or]:"Provided owner is not allowed",[jn]:"Account is immutable",[Jn]:"Incorrect authority provided",[ln]:"incorrect program id for instruction",[En]:"insufficient funds for instruction",[_n]:"invalid account data for instruction",[tr]:"Invalid account owner",[un]:"invalid program argument",[Fn]:"program returned invalid error code",[In]:"invalid instruction data",[Kn]:"Failed to reallocate account data",[Vn]:"Provided seeds do not result in a valid address",[ir]:"Accounts data allocations exceeded the maximum allowed per transaction",[ar]:"Max accounts exceeded",[sr]:"Max instruction trace length exceeded",[Hn]:"Length of the seed is too long for address generation",[xn]:"An account required by the instruction is missing",[Rn]:"missing required signature for instruction",[Nn]:"instruction illegally modified the program id of an account",[Mn]:"insufficient account keys for instruction",[Yn]:"Cross-program invocation with unauthorized signer or writable account",[Xn]:"Failed to create program execution environment",[qn]:"Program failed to compile",[Zn]:"Program failed to complete",[fn]:"instruction modified data of a read-only account",[On]:"instruction changed the balance of a read-only account",[Gn]:"Cross-program invocation reentrancy not allowed for this instruction",[hn]:"instruction modified rent epoch of an account",[gn]:"sum of account balances before and after instruction do not match",[Dn]:"instruction requires an initialized account",[cn]:"",[kn]:"Unsupported program id",[rr]:"Unsupported sysvar",[Ei]:"Invalid instruction plan kind: $kind.",[Lo]:"The provided instruction plan is empty.",[Uo]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute and the `cause` error for more details.",[Mo]:"The provided message has insufficient capacity to accommodate the next instruction(s) in this plan. Expected at least $numBytesRequired free byte(s), got $numFreeBytes byte(s).",[li]:"Invalid transaction plan kind: $kind.",[yo]:"No more instructions to pack; the message packer has completed the instruction plan.",[on]:"The instruction does not have any accounts.",[an]:"The instruction does not have any data.",[sn]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[ct]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[it]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[Ii]:"Invariant violation: Found no abortable iterable cache entry for key `$cacheKey`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[Ai]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[ui]:"Invariant violation: WebSocket message iterator state is corrupt; iterated without first resolving existing message promise. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[di]:"Invariant violation: WebSocket message iterator is missing state storage. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[_i]:"Invariant violation: Switch statement non-exhaustive. Received unexpected value `$unexpectedValue`. It should be impossible to hit this error; please file an issue at https://sola.na/web3invariant",[lt]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Rt]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Dt]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Tt]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Et]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[pt]:"$__serverMessage",[zt]:"$__serverMessage",[Pt]:"$__serverMessage",[ft]:"$__serverMessage",[Ct]:"Epoch rewards period still active at slot $slot",[Mt]:"$__serverMessage",[yt]:"$__serverMessage",[gt]:"Failed to query long-term storage; please try again",[St]:"Minimum context slot has not been reached",[bt]:"Node is unhealthy; behind by $numSlotsBehind slots",[Lt]:"No snapshot",[Bt]:"Transaction simulation failed",[Nt]:"Rewards cannot be found because slot $slot is not the epoch boundary. This may be due to gap in the queried node's local ledger or long-term storage",[Ut]:"$__serverMessage",[ht]:"Transaction history is not available from this node",[vt]:"$__serverMessage",[mt]:"Transaction signature length mismatch",[Ft]:"Transaction signature verification failure",[Ot]:"$__serverMessage",[Qt]:"Key pair bytes must be of length 64, got $byteLength.",[en]:"Expected private key bytes with length 32. Actual length: $actualLength.",[tn]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[rn]:"The provided private key does not match the provided public key.",[nn]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[dt]:"Lamports value must be in the range [0, 2e64-1]",[ut]:"`$value` cannot be parsed as a `BigInt`",[At]:"$message",[It]:"`$value` cannot be parsed as a `Number`",[at]:"No nonce account could be found at address `$nonceAccountAddress`",[oi]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[ai]:"WebSocket was closed before payload could be added to the send buffer",[si]:"WebSocket connection closed",[ci]:"WebSocket failed to connect",[ii]:"Failed to obtain a subscription id from the server",[ri]:"Could not find an API plan for RPC method: `$method`",[ei]:"The $argumentLabel argument to the `$methodName` RPC method$optionalPathLabel was `$value`. This number is unsafe for use with the Solana JSON-RPC because it exceeds `Number.MAX_SAFE_INTEGER`.",[ni]:"HTTP error ($statusCode): $message",[ti]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[dr]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[ur]:"The provided value does not implement the `KeyPairSigner` interface",[_r]:"The provided value does not implement the `MessageModifyingSigner` interface",[Ar]:"The provided value does not implement the `MessagePartialSigner` interface",[Ir]:"The provided value does not implement any of the `MessageSigner` interfaces",[lr]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Rr]:"The provided value does not implement the `TransactionPartialSigner` interface",[Tr]:"The provided value does not implement the `TransactionSendingSigner` interface",[Er]:"The provided value does not implement any of the `TransactionSigner` interfaces",[Dr]:"More than one `TransactionSendingSigner` was identified.",[gr]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Nr]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[jt]:"Cannot export a non-extractable key.",[Kt]:"No digest implementation could be found.",[Vt]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[$t]:`This runtime does not support the generation of Ed25519 key pairs.
2
2
 
3
3
  Install @solana/webcrypto-ed25519-polyfill and call its \`install\` function before generating keys in environments that do not support Ed25519.
4
4
 
5
- For a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.`,[st]:"No signature verification implementation could be found.",[ct]:"No key generation implementation could be found.",[dt]:"No signing implementation could be found.",[ut]:"No key export implementation could be found.",[pe]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[Nr]:"Transaction processing left an account with an outstanding borrowed reference",[or]:"Account in use",[ar]:"Account loaded twice",[sr]:"Attempt to debit an account but found no record of a prior credit.",[Mr]:"Transaction loads an address table account that doesn't exist",[Ir]:"This transaction has already been processed",[_r]:"Blockhash not found",[Ar]:"Loader call chain is too deep",[gr]:"Transactions are currently disabled due to cluster maintenance",[Fr]:"Transaction contains a duplicate instruction ($index) that is not allowed",[dr]:"Insufficient funds for fee",[br]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[ur]:"This account may not be used to pay transaction fees",[Rr]:"Transaction contains an invalid account reference",[yr]:"Transaction loads an address table account with invalid data",[Lr]:"Transaction address table lookup uses an invalid index",[hr]:"Transaction loads an address table account with an invalid owner",[zr]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[lr]:"This program may not be used for executing instructions",[Ur]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[Sr]:"Transaction loads a writable account that cannot be written",[Br]:"Transaction exceeded max loaded accounts data size cap",[Er]:"Transaction requires a fee but has no signature present",[cr]:"Attempt to load a program that does not exist",[kr]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[wr]:"ResanitizationNeeded",[Dr]:"Transaction failed to sanitize accounts offsets correctly",[Tr]:"Transaction did not pass signature verification",[pr]:"Transaction locked too many accounts",[xr]:"Sum of account balances before and after transaction do not match",[ir]:"The transaction failed with the error `$errorName`",[Or]:"Transaction version is unsupported",[mr]:"Transaction would exceed account data limit within the block",[Pr]:"Transaction would exceed total account data limit",[fr]:"Transaction would exceed max account limit within the block",[Cr]:"Transaction would exceed max Block Cost Limit",[vr]:"Transaction would exceed max Vote Cost Limit",[qn]:"Attempted to sign a transaction with an address that is not a signer for it",[Kn]:"Transaction is missing an address at index: $index.",[jn]:"Transaction has no expected signers therefore it cannot be encoded",[tr]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[zn]:"Transaction does not have a blockhash lifetime",[wn]:"Transaction is not a durable nonce transaction",[xn]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Wn]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[Vn]:"No fee payer set in CompiledTransaction",[Gn]:"Could not find program address at index $index",[Qn]:"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",[er]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[$n]:"Transaction is missing a fee payer.",[Yn]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Zn]:"Transaction first instruction is not advance nonce account instruction.",[Xn]:"Transaction with no instructions cannot be durable nonce transaction.",[bn]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Bn]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Jn]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Hn]:"Transaction is missing signatures for addresses: $addresses.",[kn]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[nr]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[rr]:"The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."},T="i",E="t";function vi(t,e={}){let n=Ui[t];if(n.length===0)return "";let r;function i(o){if(r[E]===2){let s=n.slice(r[T]+1,o);a.push(s in e?`${e[s]}`:`$${s}`);}else r[E]===1&&a.push(n.slice(r[T],o));}let a=[];return n.split("").forEach((o,s)=>{if(s===0){r={[T]:0,[E]:n[0]==="\\"?0:n[0]==="$"?2:1};return}let c;switch(r[E]){case 0:c={[T]:s,[E]:1};break;case 1:o==="\\"?c={[T]:s,[E]:0}:o==="$"&&(c={[T]:s,[E]:2});break;case 2:o==="\\"?c={[T]:s,[E]:0}:o==="$"?c={[T]:s,[E]:2}:o.match(/\w/)||(c={[T]:s,[E]:1});break}c&&(r!==c&&i(s),r=c);}),i(),a.join("")}function Pi(t,e={}){if(process.env.NODE_ENV!=="production")return vi(t,e);{let n=`Solana error #${t}; Decode this error by running \`npx @solana/errors decode -- ${t}`;return Object.keys(e).length&&(n+=` '${Li(e)}'`),`${n}\``}}var C=class extends Error{cause=this.cause;context;constructor(...[t,e]){let n,r;e&&Object.entries(Object.getOwnPropertyDescriptors(e)).forEach(([a,o])=>{a==="cause"?r={cause:o.value}:(n===void 0&&(n={}),Object.defineProperty(n,a,o));});let i=Pi(t,n);super(i,r),this.context=n===void 0?{}:n,this.context.__code=t,this.name="SolanaError";}};function Fi(t,e){return "fixedSize"in e?e.fixedSize:e.getSizeFromValue(t)}function O(t){return Object.freeze({...t,encode:e=>{let n=new Uint8Array(Fi(e,t));return t.write(e,n,0),n}})}function v(t){return Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]})}function bi(t){return "fixedSize"in t&&typeof t.fixedSize=="number"}function Bi(t){return !bi(t)}function X(t,e){return O({fixedSize:e,write:(n,r,i)=>{let a=t.encode(n),o=a.length>e?a.slice(0,e):a;return r.set(o,i),i+e}})}function Z(t,e){return O({...Bi(t)?{...t,getSizeFromValue:n=>t.getSizeFromValue(e(n))}:t,write:(n,r,i)=>t.write(e(n),r,i)})}function zi(t,e,n=e){if(!e.match(new RegExp(`^[${t}]*$`)))throw new C(U,{alphabet:t,base:t.length,value:n})}var wi=t=>O({getSizeFromValue:e=>{let[n,r]=q(e,t[0]);if(!r)return e.length;let i=j(r,t);return n.length+Math.ceil(i.toString(16).length/2)},write(e,n,r){if(zi(t,e),e==="")return r;let[i,a]=q(e,t[0]);if(!a)return n.set(new Uint8Array(i.length).fill(0),r),r+i.length;let o=j(a,t),s=[];for(;o>0n;)s.unshift(Number(o%256n)),o/=256n;let c=[...Array(i.length).fill(0),...s];return n.set(c,r),r+c.length}});function q(t,e){let[n,r]=t.split(new RegExp(`((?!${e}).*)`));return [n,r]}function j(t,e){let n=BigInt(e.length),r=0n;for(let i of t)r*=n,r+=BigInt(e.indexOf(i));return r}var ki="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Q=()=>wi(ki);var D=()=>v({read:(t,e=0)=>[Buffer.from(t,e).toString("base64"),t.length]});var P;function ee(){return P||(P=Q()),P}function xi(t){if(t.length<32||t.length>44)throw new C(y,{actualLength:t.length});let r=ee().encode(t).byteLength;if(r!==32)throw new C(h,{actualLength:r})}function S(t){return xi(t),t}function F(){return Z(X(ee(),32),t=>S(t))}function Wi(t,e,n,r){if(r<e||r>n)throw new C(L,{codecDescription:t,max:n,min:e,value:r})}function Gi(t){return t?.endian!==1}function Vi(t){return O({fixedSize:t.size,write(e,n,r){t.range&&Wi(t.name,t.range[0],t.range[1],e);let i=new ArrayBuffer(t.size);return t.set(new DataView(i),e,Gi(t.config)),n.set(new Uint8Array(i),r),r+t.size}})}var te=(t={})=>Vi({config:t,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,n,r)=>e.setBigUint64(0,BigInt(n),r),size:8});function ne(t){if(typeof window>"u")throw new Error("Function can only be called in a browser environment");let e=window.innerWidth||window.screen.availWidth,n=window.innerHeight||window.screen.availHeight,r=e<=768,i,a,o,s;if(r)i=e,a=n,o=0,s=0;else {let I=window.screenLeft??window.screenX??0,_=window.screenTop??window.screenY??0,d=window.innerWidth??document.documentElement.clientWidth??window.screen.width,u=window.innerHeight??document.documentElement.clientHeight??window.screen.height;i=500,a=600,s=Math.round(I+(d-i)/2),o=Math.round(_+(u-a)/2);}let c=["popup=yes",`width=${i}`,`height=${a}`,`top=${o}`,`left=${s}`,"toolbar=no","location=no","status=no","menubar=no","scrollbars=yes","resizable=yes"].join(",");return window.open(t??"","_blank",c)}function re(t){let e=t.domain?`${t.domain} wants you to sign in with your account.`:"Sign in with your account.",n=[];return t.nonce&&n.push(`Nonce: ${t.nonce}`),n.length>0?`${e}
5
+ For a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.`,[Yt]:"No signature verification implementation could be found.",[Xt]:"No key generation implementation could be found.",[Zt]:"No signing implementation could be found.",[qt]:"No key export implementation could be found.",[_t]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[ao]:"Transaction processing left an account with an outstanding borrowed reference",[Kr]:"Account in use",[$r]:"Account loaded twice",[Yr]:"Attempt to debit an account but found no record of a prior credit.",[Eo]:"Transaction loads an address table account that doesn't exist",[jr]:"This transaction has already been processed",[Jr]:"Blockhash not found",[Qr]:"Loader call chain is too deep",[io]:"Transactions are currently disabled due to cluster maintenance",[Co]:"Transaction contains a duplicate instruction ($index) that is not allowed",[Zr]:"Insufficient funds for fee",[So]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[qr]:"This account may not be used to pay transaction fees",[to]:"Transaction contains an invalid account reference",[Ro]:"Transaction loads an address table account with invalid data",[To]:"Transaction address table lookup uses an invalid index",[lo]:"Transaction loads an address table account with an invalid owner",[fo]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[ro]:"This program may not be used for executing instructions",[Do]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[uo]:"Transaction loads a writable account that cannot be written",[Oo]:"Transaction exceeded max loaded accounts data size cap",[eo]:"Transaction requires a fee but has no signature present",[Xr]:"Attempt to load a program that does not exist",[po]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[mo]:"ResanitizationNeeded",[oo]:"Transaction failed to sanitize accounts offsets correctly",[no]:"Transaction did not pass signature verification",[Ao]:"Transaction locked too many accounts",[ho]:"Sum of account balances before and after transaction do not match",[Vr]:"The transaction failed with the error `$errorName`",[co]:"Transaction version is unsupported",[_o]:"Transaction would exceed account data limit within the block",[No]:"Transaction would exceed total account data limit",[Io]:"Transaction would exceed max account limit within the block",[so]:"Transaction would exceed max Block Cost Limit",[go]:"Transaction would exceed max Vote Cost Limit",[Br]:"Attempted to sign a transaction with an address that is not a signer for it",[Ur]:"Transaction is missing an address at index: $index.",[zr]:"Transaction has no expected signers therefore it cannot be encoded",[xr]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Or]:"Transaction does not have a blockhash lifetime",[fr]:"Transaction is not a durable nonce transaction",[pr]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[hr]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[yr]:"No fee payer set in CompiledTransaction",[Mr]:"Could not find program address at index $index",[kr]:"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",[Wr]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[vr]:"Transaction is missing a fee payer.",[br]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Fr]:"Transaction first instruction is not advance nonce account instruction.",[Pr]:"Transaction with no instructions cannot be durable nonce transaction.",[Cr]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Sr]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[wr]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Lr]:"Transaction is missing signatures for addresses: $addresses.",[mr]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[Gr]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[Hr]:"The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."},h="i",O="t";function gi(t,e={}){let n=Di[t];if(n.length===0)return "";let r;function i(o){if(r[O]===2){let c=n.slice(r[h]+1,o);s.push(c in e?`${e[c]}`:`$${c}`);}else r[O]===1&&s.push(n.slice(r[h],o));}let s=[];return n.split("").forEach((o,c)=>{if(c===0){r={[h]:0,[O]:n[0]==="\\"?0:n[0]==="$"?2:1};return}let a;switch(r[O]){case 0:a={[h]:c,[O]:1};break;case 1:o==="\\"?a={[h]:c,[O]:0}:o==="$"&&(a={[h]:c,[O]:2});break;case 2:o==="\\"?a={[h]:c,[O]:0}:o==="$"?a={[h]:c,[O]:2}:o.match(/\w/)||(a={[h]:c,[O]:1});break}a&&(r!==a&&i(c),r=a);}),i(),s.join("")}function Ni(t,e={}){if(process.env.NODE_ENV!=="production")return gi(t,e);{let n=`Solana error #${t}; Decode this error by running \`npx @solana/errors decode -- ${t}`;return Object.keys(e).length&&(n+=` '${Ti(e)}'`),`${n}\``}}var P=class extends Error{cause=this.cause;context;constructor(...[t,e]){let n,r;e&&Object.entries(Object.getOwnPropertyDescriptors(e)).forEach(([s,o])=>{s==="cause"?r={cause:o.value}:(n===void 0&&(n={}),Object.defineProperty(n,s,o));});let i=Ni(t,n);super(i,r),this.context=n===void 0?{}:n,this.context.__code=t,this.name="SolanaError";}};function Ci(t,e){return "fixedSize"in e?e.fixedSize:e.getSizeFromValue(t)}function z(t){return Object.freeze({...t,encode:e=>{let n=new Uint8Array(Ci(e,t));return t.write(e,n,0),n}})}function ce(t){return Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]})}function Si(t){return "fixedSize"in t&&typeof t.fixedSize=="number"}function Oi(t){return !Si(t)}function he(t,e){return z({fixedSize:e,write:(n,r,i)=>{let s=t.encode(n),o=s.length>e?s.slice(0,e):s;return r.set(o,i),i+e}})}function Me(t,e){return z({...Oi(t)?{...t,getSizeFromValue:n=>t.getSizeFromValue(e(n))}:t,write:(n,r,i)=>t.write(e(n),r,i)})}function fi(t,e,n=e){if(!e.match(new RegExp(`^[${t}]*$`)))throw new P(se,{alphabet:t,base:t.length,value:n})}var mi=t=>z({getSizeFromValue:e=>{let[n,r]=ye(e,t[0]);if(!r)return e.length;let i=Le(r,t);return n.length+Math.ceil(i.toString(16).length/2)},write(e,n,r){if(fi(t,e),e==="")return r;let[i,s]=ye(e,t[0]);if(!s)return n.set(new Uint8Array(i.length).fill(0),r),r+i.length;let o=Le(s,t),c=[];for(;o>0n;)c.unshift(Number(o%256n)),o/=256n;let a=[...Array(i.length).fill(0),...c];return n.set(a,r),r+a.length}});function ye(t,e){let[n,r]=t.split(new RegExp(`((?!${e}).*)`));return [n,r]}function Le(t,e){let n=BigInt(e.length),r=0n;for(let i of t)r*=n,r+=BigInt(e.indexOf(i));return r}var pi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ve=()=>mi(pi);var v=()=>ce({read:(t,e=0)=>[Buffer.from(t,e).toString("base64"),t.length]});var de;function be(){return de||(de=ve()),de}function hi(t){if(t.length<32||t.length>44)throw new P(ie,{actualLength:t.length});let r=be().encode(t).byteLength;if(r!==32)throw new P(oe,{actualLength:r})}function w(t){return hi(t),t}function ue(){return Me(he(be(),32),t=>w(t))}function Mi(t,e,n,r){if(r<e||r>n)throw new P(ae,{codecDescription:t,max:n,min:e,value:r})}function yi(t){return t?.endian!==1}function Li(t){return z({fixedSize:t.size,write(e,n,r){t.range&&Mi(t.name,t.range[0],t.range[1],e);let i=new ArrayBuffer(t.size);return t.set(new DataView(i),e,yi(t.config)),n.set(new Uint8Array(i),r),r+t.size}})}var Pe=(t={})=>Li({config:t,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,n,r)=>e.setBigUint64(0,BigInt(n),r),size:8});var k="https://auth.revibase.com";var Fe="revibase.com";var f=class t extends Error{code;constructor(e,n){super(e),this.name="RevibaseError",this.code=n,Object.setPrototypeOf(this,t.prototype);}},j=class t extends f{constructor(e="Popup blocked. Please enable popups."){super(e,"POPUP_BLOCKED"),this.name="RevibasePopupBlockedError",Object.setPrototypeOf(this,t.prototype);}},V=class t extends f{constructor(e="Popup was closed by the user"){super(e,"POPUP_CLOSED"),this.name="RevibasePopupClosedError",Object.setPrototypeOf(this,t.prototype);}},K=class t extends f{constructor(e="Authentication timed out"){super(e,"TIMEOUT"),this.name="RevibaseTimeoutError",Object.setPrototypeOf(this,t.prototype);}},J=class t extends f{constructor(e="An authorization flow is already in progress"){super(e,"FLOW_IN_PROGRESS"),this.name="RevibaseFlowInProgressError",Object.setPrototypeOf(this,t.prototype);}},$=class t extends f{constructor(e="Aborted"){super(e,"ABORTED"),this.name="RevibaseAbortedError",Object.setPrototypeOf(this,t.prototype);}},Q=class t extends f{constructor(e="Popup is not open. Call startRequest first."){super(e,"POPUP_NOT_OPEN"),this.name="RevibasePopupNotOpenError",Object.setPrototypeOf(this,t.prototype);}},F=class t extends f{constructor(e){super(e,"AUTH_FAILED"),this.name="RevibaseAuthError",Object.setPrototypeOf(this,t.prototype);}},ee=class t extends f{constructor(e="Provider can only be used in a browser environment"){super(e,"ENVIRONMENT"),this.name="RevibaseEnvironmentError",Object.setPrototypeOf(this,t.prototype);}};var bi="device-keys",W="ed25519-keys",Be="private-key",ze="public-key",B=class t{static openDB(){return new Promise((e,n)=>{let r=indexedDB.open(bi,1);r.onupgradeneeded=()=>{let i=r.result;i.objectStoreNames.contains(W)||i.createObjectStore(W);},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error);})}static async saveToDB(e,n){let r=await t.openDB();return new Promise((i,s)=>{let o=r.transaction(W,"readwrite");o.objectStore(W).put(n,e),o.oncomplete=()=>i(),o.onerror=()=>s(o.error);})}static async loadFromDB(e){let n=await t.openDB();return new Promise((r,i)=>{let o=n.transaction(W,"readonly").objectStore(W).get(e);o.onsuccess=()=>r(o.result),o.onerror=()=>i(o.error);})}static async create(){let e=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",e.publicKey),r=core.convertJWKToBase64String({...n,alg:"EdDSA"});try{await t.saveToDB(Be,e.privateKey);}catch(i){throw i instanceof DOMException&&i.name==="DataCloneError"?new Error("Storing device key in this browser is not supported. Try Chrome or ensure you are in a secure context."):i}return await t.saveToDB(ze,r),r}static async getOrCreateDevicePublickey(){let e=await t.loadFromDB(ze);return e||(e=await t.create()),{publicKey:e}}static async sign(e){let n=await t.loadFromDB(Be);if(!n)throw new Error("Device key not found. Call DeviceKeyManager.create() first.");return await new jose.CompactSign(e).setProtectedHeader({alg:"EdDSA"}).sign(n)}};function we(t){if(typeof window>"u")throw new Error("Function can only be called in a browser environment");let e=window.innerWidth||window.screen.availWidth,n=window.innerHeight||window.screen.availHeight,r=e<=768,i,s,o,c;if(r)i=e,s=n,o=0,c=0;else {let l=window.screenLeft??window.screenX??0,R=window.screenTop??window.screenY??0,E=window.innerWidth??document.documentElement.clientWidth??window.screen.width,D=window.innerHeight??document.documentElement.clientHeight??window.screen.height;i=500,s=600,c=Math.round(l+(E-i)/2),o=Math.round(R+(D-s)/2);}let a=["popup=yes",`width=${i}`,`height=${s}`,`top=${o}`,`left=${c}`,"toolbar=no","location=no","status=no","menubar=no","scrollbars=yes","resizable=yes"].join(",");return window.open(t??"","_blank",a)}var Pi=3,Fi=1e3,Bi=1e4,zi=3e4,wi=1e4,ki=64*1024,Wi=1008,xi=1009;function Gi(t,e){return typeof t=="string"?new TextEncoder().encode(t).length<=e?t:null:t.byteLength>e?null:new TextDecoder().decode(t)}var Hi=_a.z.object({event:_a.z.literal("awaiting_recipient")}),Vi=_a.z.object({event:_a.z.literal("recipient_connected"),data:_a.z.object({devicePublicKey:_a.z.string()})}),Ki=_a.z.object({event:_a.z.literal("recipient_disconnected")}),$i=_a.z.discriminatedUnion("event",[Hi,Vi,Ki]);function Yi(t){try{let e=JSON.parse(t),n=$i.safeParse(e);return n.success?n.data:null}catch{return null}}function ke(t){let{providerOrigin:e,channelId:n,getDevicePayload:r,callbacks:i,maxReconnectAttempts:s=Pi,reconnectBaseDelayMs:o=Fi,authTimeoutMs:c=Bi,maxMessageBytes:a=ki,verboseLogging:l=false,heartbeatIntervalMs:R=zi,heartbeatTimeoutMs:E=wi}=t,{onAwaitingRecipient:D,onRecipientConnected:L,onRecipientDisconnected:m,onClose:T,onError:U,onConnectionLost:Y,onAutoReconnecting:Je,onConnected:Qe}=i,Ae=new URL(e),et=Ae.protocol==="https:"?"wss:":"ws:",tt=Ae.host,ne=`${et}//${tt}/api/channel/ws?channelId=${encodeURIComponent(n)}`,I=t.logger??console;I.info("[Channel WS Sender] Creating socket",{channelId:n,wsUrl:ne});let A=new WebSocket(ne),_=false,re=false,N=false,C=0,G=null,X=null,p=null,b=false;function Z(){G!=null&&(clearTimeout(G),G=null);}function q(){X!=null&&(clearInterval(X),X=null),p!=null&&(clearTimeout(p),p=null);}function Ee(u,d){if(!_){_=true,re=true,N=false,Z(),q();try{(A.readyState===WebSocket.OPEN||A.readyState===WebSocket.CONNECTING)&&A.close(u??1e3,d??"Closed");}catch{}}}async function nt(u){let d,S=new Promise((g,H)=>{d=setTimeout(()=>H(new Error("Auth timeout")),c);});try{return await Promise.race([r(u),S])}finally{d!=null&&clearTimeout(d);}}function rt(u,d,S){u.onopen=null,u.onclose=null,u.onerror=null,u.onmessage=null;try{(u.readyState===WebSocket.OPEN||u.readyState===WebSocket.CONNECTING)&&u.close(d??1e3,S??"Reconnecting");}catch{}}function le(){let u=A;A=new WebSocket(ne),Re(A),rt(u,1e3,"Reconnecting");}function Re(u){u.onopen=async()=>{if(!_){I.info("[Channel WS Sender] Socket opened",{channelId:n});try{let d=await nt(n);if(_||u.readyState!==WebSocket.OPEN)return;u.send(JSON.stringify({type:"auth",device:d})),I.info("[Channel WS Sender] Auth sent",{channelId:n}),C=0,Qe?.(),R>0&&E>0&&(X=setInterval(()=>{if(!(_||A.readyState!==WebSocket.OPEN)){if(p!=null){I.warn("[Channel WS Sender] Heartbeat timeout",{channelId:n}),b=!0,q();try{A.close(1e3,"Heartbeat timeout");}catch{}return}try{A.send(JSON.stringify({type:"ping"}));}catch{return}p=setTimeout(()=>{if(p=null,!_){I.warn("[Channel WS Sender] Heartbeat timeout",{channelId:n}),b=!0,q();try{A.close(1e3,"Heartbeat timeout");}catch{}}},E);}},R));}catch(d){I.error("Channel WebSocket (sender) auth failed",d,{channelId:n}),U?.("Auth failed"),Ee(Wi,"Auth failed");}}},u.onmessage=d=>{if(_)return;let S=Gi(d.data,a);if(S===null){I.warn("[Channel WS Sender] Message too large or invalid",{channelId:n}),re=true,Z();try{u.close(xi,"Message too large");}catch{}return}try{if(JSON.parse(S)?.event==="pong"){p!=null&&(clearTimeout(p),p=null);return}}catch{}let g=Yi(S);if(!g){l&&I.info("[Channel WS Sender] Unparseable message",{channelId:n,preview:S.slice(0,100)});return}l&&I.info("[Channel WS Sender] Message received",{channelId:n,event:g.event,...g.event!=="awaiting_recipient"&&g.event!=="recipient_disconnected"&&{data:g.data}}),g.event==="awaiting_recipient"?D?.():g.event==="recipient_connected"?L?.(g.data):g.event==="recipient_disconnected"&&m?.();},u.onclose=d=>{if(q(),d.target!==A)return;if(_&&!b){T?.({code:d.code,reason:d.reason||"",wasClean:d.wasClean});return}if(b?I.info("[Channel WS Sender] Socket closed (heartbeat timeout)",{channelId:n,code:d.code,reason:d.reason||"(none)",retryCount:C}):_||I.info("[Channel WS Sender] Socket closed",{channelId:n,code:d.code,reason:d.reason||"(none)",wasClean:d.wasClean,retryCount:C}),re){_=true,T?.({code:d.code,reason:d.reason||"",wasClean:d.wasClean});return}if(d.wasClean&&!b){_=true,T?.({code:d.code,reason:d.reason||"",wasClean:d.wasClean});return}if(b&&(b=false),C>=s){_=true,N=true,I.info("[Channel WS Sender] Max reconnect attempts reached",{channelId:n,maxReconnectAttempts:s}),Y?.();return}let S=o*Math.pow(2,C),g=.8+.4*Math.random(),H=Math.min(Math.round(S*g),3e4);C+=1,Je?.(C),I.info("[Channel WS Sender] Scheduling reconnect",{channelId:n,attempt:C,delayMs:H}),G=setTimeout(()=>{G=null,!_&&(I.info("[Channel WS Sender] Reconnecting",{channelId:n,attempt:C}),le());},H);},u.onerror=()=>{I.info("[Channel WS Sender] Socket error",{channelId:n}),_||U?.("Connection error");};}return Re(A),{reconnect(){return _||!N?(I.info("[Channel WS Sender] reconnect() no-op",{channelId:n,closed:_,connectionLost:N}),false):(I.info("[Channel WS Sender] reconnect() starting",{channelId:n}),N=false,C=0,Z(),le(),true)},closeChannel(){if(!_&&!N&&A.readyState===WebSocket.OPEN)try{I.info("[Channel WS Sender] Sending close",{channelId:n}),A.send(JSON.stringify({type:"close"}));}catch(u){I.error("Channel close send failed",u,{channelId:n}),U?.("Failed to close channel");}else _||I.info("[Channel WS Sender] closeChannel skip send",{channelId:n,closed:_,connectionLost:N,readyState:A.readyState});if(!_){if(I.info("[Channel WS Sender] close() called",{channelId:n,connectionLost:N}),N){_=true,N=false,Z(),T?.({code:1e3,reason:"Closed",wasClean:true});return}Ee();}},cancelRequest(){if(_||N||A.readyState!==WebSocket.OPEN)return I.info("[Channel WS Sender] cancelRequest() skipped",{channelId:n,readyState:A.readyState}),false;try{return I.info("[Channel WS Sender] Sending cancel_request",{channelId:n}),A.send(JSON.stringify({type:"cancel_request"})),!0}catch(u){return I.error("Channel (sender) cancel_request send failed",u,{channelId:n}),U?.("Failed to cancel request"),false}}}}var qi=(a=>(a[a.AUTHENTICATING=0]="AUTHENTICATING",a[a.AWAITING_RECIPIENT=1]="AWAITING_RECIPIENT",a[a.RECIPIENT_CONNECTED=2]="RECIPIENT_CONNECTED",a[a.RECIPIENT_DISCONNECTED=3]="RECIPIENT_DISCONNECTED",a[a.AUTO_RECONNECTING=4]="AUTO_RECONNECTING",a[a.CONNECTION_LOST=5]="CONNECTION_LOST",a[a.CHANNEL_CLOSED=6]="CHANNEL_CLOSED",a[a.ERROR=7]="ERROR",a))(qi||{}),We=class{pending=new Map;onClientAuthorizationCallback;providerOrigin;popUp=null;channelWs=new Map;channelStatusListeners=new Set;logger;defaultCallback=async(e,n,r,i)=>{let s=await fetch("/api/clientAuthorization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({request:e,device:r,channelId:i}),signal:n}),o=await s.json();if(!s.ok)throw new F(o.error??"Authorization failed");return o};constructor(e={}){let{providerOrigin:n,onClientAuthorizationCallback:r,rpcEndpoint:i,logger:s}=e;this.onClientAuthorizationCallback=r??this.defaultCallback,this.providerOrigin=n??k,this.logger=s??{info:()=>{},warn:()=>{},error:()=>{}},i&&core.initialize({rpcEndpoint:i});}async getDeviceSignature(e){return {jwk:(await B.getOrCreateDevicePublickey()).publicKey,jws:await B.sign(new TextEncoder().encode(e))}}subscribeToChannelStatus(e){return this.channelStatusListeners.add(e),()=>{this.channelStatusListeners.delete(e);}}setChannelStatus(e,n){for(let r of this.channelStatusListeners)try{r(e,n);}catch(i){this.logger.error("[RevibaseProvider] Channel status listener threw",i);}}async createChannel(){let e=await fetch(`${this.providerOrigin}/api/channel/challenge`);if(!e.ok){let a=await e.json();throw new F(a.error??"Unable to generate challenge")}let{id:n,challenge:r}=await e.json(),i={jwk:(await B.getOrCreateDevicePublickey()).publicKey,jws:await B.sign(new TextEncoder().encode(r))},s=await fetch(`${this.providerOrigin}/api/channel/create`,{method:"POST",body:JSON.stringify({device:i,challengeId:n})});if(!s.ok){let a=await s.json();throw new F(a.error??"Unable to create channel")}let{channelId:o}=await s.json(),c=ke({channelId:o,getDevicePayload:this.getDeviceSignature,providerOrigin:this.providerOrigin,callbacks:{onAwaitingRecipient:()=>this.setChannelStatus(o,{status:1}),onRecipientConnected:({devicePublicKey:a})=>this.setChannelStatus(o,{status:2,recipient:a}),onRecipientDisconnected:()=>this.setChannelStatus(o,{status:3}),onClose:()=>{this.setChannelStatus(o,{status:6}),this.channelWs.delete(o);},onError:a=>this.setChannelStatus(o,{status:7,error:a}),onConnectionLost:()=>this.setChannelStatus(o,{status:5}),onAutoReconnecting:a=>this.setChannelStatus(o,{status:4,reconnectAttempt:a})}});return this.channelWs.set(o,c),this.setChannelStatus(o,{status:0}),{channelId:o,url:`${this.providerOrigin}?channelId=${o}`}}cancelChannelRequest(e){this.channelWs.get(e)?.cancelRequest();}reconnectChannel(e){return this.channelWs.get(e)?.reconnect()??false}closeChannel(e){this.channelWs.get(e)?.closeChannel(),this.channelWs.delete(e);}closeAllChannels(){this.channelWs.entries().forEach(e=>e[1].closeChannel()),this.channelWs.clear();}startRequest(e){let n=window.origin,r=v().decode(crypto.getRandomValues(new Uint8Array(16)));if(!e){let i=new URL(this.providerOrigin);if(i.searchParams.set("rid",r),i.searchParams.set("redirectOrigin",n),this.popUp=we(i.toString()),!this.popUp)throw new j}return {rid:r,redirectOrigin:n}}async sendPayloadToProviderViaPopup({rid:e,timeoutMs:n=6e5,signal:r}){if(typeof window>"u")throw new ee;if(this.pending.size>0)throw new J;return new Promise((i,s)=>{let o=setTimeout(()=>{let c=this.pending.get(e);c&&(c.cancel?c.cancel(new K):(this.pending.delete(e),s(new K)));},n);if(!this.popUp||this.popUp.closed)throw new Q;this.pending.set(e,{rid:e,resolve:i,reject:s,timeoutId:o}),this.attachTransport({popup:this.popUp,origin:new URL(this.providerOrigin).origin,rid:e,signal:r});})}attachTransport(e){let{popup:n,origin:r,rid:i,signal:s}=e,o=this.pending.get(i);if(!o)return;let c=null,a=false,l=()=>{E(new $);},R=()=>{s.removeEventListener("abort",l),window.removeEventListener("message",m);try{c?.close();}catch{}c=null;try{n&&!n.closed&&n.close();}catch{}this.popUp=null,clearInterval(L);},E=T=>{a||(a=true,clearTimeout(o.timeoutId),this.pending.delete(i),R(),o.reject(T));},D=()=>{a||(a=true,clearTimeout(o.timeoutId),this.pending.delete(i),R(),o.resolve({rid:i}));};if(o.cancel=E,s.aborted){E(new $);return}s.addEventListener("abort",l);let L=setInterval(()=>{n?.closed&&E(new V);},2e3),m=T=>{if(T.origin!==r||T.source!==n)return;let U=T.data;!U||U.type!=="popup-connect"||U.rid!==i||T.ports?.[0]&&(c=T.ports[0],c.start(),c.postMessage({type:"popup-init"}),c.onmessage=Y=>{switch(Y.data.type){case "popup-complete":D();break;case "popup-error":E(new F(Y.data.error));break;case "popup-closed":{E(new V("Lost connection with the popup."));break}}},window.removeEventListener("message",m));};window.addEventListener("message",m);}};function xe(t){let e=t.domain?`${t.domain} wants you to sign in with your account.`:"Sign in with your account.",n=[];return t.nonce&&n.push(`Nonce: ${t.nonce}`),n.length>0?`${e}
6
6
 
7
7
  ${n.join(`
8
- `)}`:e}async function bo(t,e){let{rid:n,redirectOrigin:r}=t.startRequest(!e);await new Promise(o=>setTimeout(o,0));let i={phase:"start",rid:n,validTill:Date.now()+6e5,data:{type:"message",payload:re({domain:r,nonce:D().decode(crypto.getRandomValues(new Uint8Array(16)))})},redirectOrigin:r},a=new AbortController;return t.sendPayloadToProviderViaPopup({rid:n,usePopUp:!e,signal:a.signal}).catch(o=>a.abort(o)),await t.onClientAuthorizationCallback(i,a.signal,await t.getDeviceSignature(n,e),e)}async function xo(t,e,n){let{redirectOrigin:r,rid:i}=t.startRequest(!n);await new Promise(g=>setTimeout(g,0));let{instructions:a,signer:o,addressesByLookupTableAddress:s,hasTxManager:c=true}=e,I=core.prepareTransactionMessage({payer:S(o.walletAddress),instructions:a,addressesByLookupTableAddress:s}),_=await core.getSettingsFromIndex(o.settingsIndexWithAddress.index),d={transactionMessageBytes:D().decode(I),transactionAddress:_,transactionActionType:c?"execute":"create_with_preauthorized_execution"},u={phase:"start",rid:i,validTill:Date.now()+6e5,data:{type:"transaction",payload:d,sendTx:true,additionalSigners:e.additionalSigners},redirectOrigin:r,signer:o.publicKey},A=new AbortController;return t.sendPayloadToProviderViaPopup({rid:i,usePopUp:!n,signal:A.signal}).catch(g=>A.abort(g)),await t.onClientAuthorizationCallback(u,A.signal,await t.getDeviceSignature(i,n),n)}var p="11111111111111111111111111111111";var ie=0,oe=1,ae=2,se=3,ce=4,de=5,ue=6,Ie=7,_e=8;process.env.NODE_ENV!=="production"&&({[ie]:"an account with the same address already exists",[de]:"provided address does not match addressed derived from seed",[se]:"cannot allocate account data of this length",[ae]:"cannot assign account to this program id",[ce]:"length of requested seed is too long",[Ie]:"stored nonce is still in recent_blockhashes",[ue]:"advancing stored nonce requires a populated RecentBlockhashes sysvar",[_e]:"specified nonce does not match stored nonce",[oe]:"account does not have enough SOL to perform the operation"});var b="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";async function _f(t,e,n){if(e.amount<=0)throw new Error("Transfer amount must be greater than 0");if(!e.destination||typeof e.destination!="string")throw new Error("Destination address is required");let{rid:r,redirectOrigin:i}=t.startRequest(!n);await new Promise(A=>setTimeout(A,0));let{mint:a,tokenProgram:o=b,amount:s,destination:c,signer:I}=e,_={transactionActionType:"transfer_intent",transactionAddress:a?o:p,transactionMessageBytes:D().decode(new Uint8Array([...te().encode(s),...F().encode(S(c)),...F().encode(S(a??p))]))},d={phase:"start",rid:r,validTill:Date.now()+6e5,data:{type:"transaction",payload:_,sendTx:true},redirectOrigin:i,signer:I?.publicKey},u=new AbortController;return t.sendPayloadToProviderViaPopup({rid:r,usePopUp:!n,signal:u.signal}).catch(A=>u.abort(A)),await t.onClientAuthorizationCallback(d,u.signal,await t.getDeviceSignature(r,n),n)}var f="https://auth.revibase.com";var Ae="revibase.com";var Zi="device-keys",m="ed25519-keys",Ee="private-key",Re="public-key",l=class t{static openDB(){return new Promise((e,n)=>{let r=indexedDB.open(Zi,1);r.onupgradeneeded=()=>{let i=r.result;i.objectStoreNames.contains(m)||i.createObjectStore(m);},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error);})}static async saveToDB(e,n){let r=await t.openDB();return new Promise((i,a)=>{let o=r.transaction(m,"readwrite");o.objectStore(m).put(n,e),o.oncomplete=()=>i(),o.onerror=()=>a(o.error);})}static async loadFromDB(e){let n=await t.openDB();return new Promise((r,i)=>{let o=n.transaction(m,"readonly").objectStore(m).get(e);o.onsuccess=()=>r(o.result),o.onerror=()=>i(o.error);})}static async create(){let e=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",e.publicKey),r=core.convertJWKToBase64String({...n,alg:"EdDSA"});try{await t.saveToDB(Ee,e.privateKey);}catch(i){throw i instanceof DOMException&&i.name==="DataCloneError"?new Error("Storing device key in this browser is not supported. Try Chrome or ensure you are in a secure context."):i}return await t.saveToDB(Re,r),r}static async getOrCreateDevicePublickey(){let e=await t.loadFromDB(Re);return e||(e=await t.create()),{publicKey:e}}static async sign(e){let n=await t.loadFromDB(Ee);if(!n)throw new Error("Device key not found. Call DeviceKeyManager.create() first.");return await new jose.CompactSign(e).setProtectedHeader({alg:"EdDSA"}).sign(n)}};var Te=class{pending=new Map;onClientAuthorizationCallback;providerOrigin;popUp=null;channelIds=[];defaultCallback=async(e,n,r,i)=>{let a=await fetch("/api/clientAuthorization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({request:e,device:r,channelId:i}),signal:n}),o=await a.json();if(!a.ok)throw new Error(o.error??"Authorization failed");return o};constructor(e,n){this.onClientAuthorizationCallback=e??this.defaultCallback,this.providerOrigin=n??f;}async getDeviceSignature(e,n){if(n)return {jwk:(await l.getOrCreateDevicePublickey()).publicKey,jws:await l.sign(new TextEncoder().encode(JSON.stringify({channelId:n,rid:e})))}}getAllChannelIds(){return this.channelIds}async closeAllChannels(){let e=new Array(...new Set(this.channelIds));return await Promise.all(e.map(n=>this.closeChannel(n)))}async createChannel(){let e=await fetch(`${this.providerOrigin}/api/channel/challenge`);if(!e.ok){let s=await e.json();throw new Error(s.error??"Unable to generate challenge")}let{id:n,challenge:r}=await e.json(),i={jwk:(await l.getOrCreateDevicePublickey()).publicKey,jws:await l.sign(new TextEncoder().encode(r))},a=await fetch(`${this.providerOrigin}/api/channel/create`,{method:"POST",body:JSON.stringify({device:i,challengeId:n})});if(!a.ok){let s=await a.json();throw new Error(s.error??"Unable to create channel")}let{channelId:o}=await a.json();return this.channelIds.push(o),{channelId:o,url:`${this.providerOrigin}?channelId=${o}`}}async closeChannel(e){let n={jwk:(await l.getOrCreateDevicePublickey()).publicKey,jws:await l.sign(new TextEncoder().encode(e))},r=await fetch(`${this.providerOrigin}/api/channel/close`,{method:"POST",body:JSON.stringify({device:n,channelId:e})});if(!r.ok){let i=await r.json();throw new Error(i.error??"Unable to close channel")}this.channelIds=this.channelIds.filter(i=>i!==e);}startRequest(e){let n=window.origin,r=D().decode(crypto.getRandomValues(new Uint8Array(16)));if(e){let i=new URL(this.providerOrigin);if(i.searchParams.set("rid",r),i.searchParams.set("redirectOrigin",n),this.popUp=ne(i.toString()),!this.popUp)throw new Error("Popup blocked. Please enable popups.")}return {rid:r,redirectOrigin:n}}async sendPayloadToProviderViaPopup({rid:e,timeoutMs:n=6e5,signal:r,usePopUp:i}){if(i){if(typeof window>"u")throw new Error("Provider can only be used in a browser environment");if(this.pending.size>0)throw new Error("An authorization flow is already in progress");return new Promise((a,o)=>{let s=setTimeout(()=>{let c=this.pending.get(e);c&&(c.cancel?c.cancel(new Error("Authentication timed out")):(this.pending.delete(e),o(new Error("Authentication timed out"))));},n);if(!this.popUp||this.popUp.closed)throw new Error("Popup is not open. Call createNewPopup() first.");this.pending.set(e,{rid:e,resolve:a,reject:o,timeoutId:s}),this.attachTransport({popup:this.popUp,origin:new URL(this.providerOrigin).origin,rid:e,signal:r});})}}attachTransport(e){let{popup:n,origin:r,rid:i,signal:a}=e,o=this.pending.get(i);if(!o)return;let s=null,c=false,I=()=>{d(new Error("Aborted"));},_=()=>{a.removeEventListener("abort",I),window.removeEventListener("message",g);try{s?.close();}catch{}s=null;try{n&&!n.closed&&n.close();}catch{}this.popUp=null,clearInterval(A);},d=N=>{c||(c=true,clearTimeout(o.timeoutId),this.pending.delete(i),_(),o.reject(N));},u=()=>{c||(c=true,clearTimeout(o.timeoutId),this.pending.delete(i),_(),o.resolve({rid:i}));};if(o.cancel=d,a.aborted){d(new Error("Aborted"));return}a.addEventListener("abort",I);let A=setInterval(()=>{n?.closed&&d(new Error("Popup was closed by the user"));},2e3),g=N=>{if(N.origin!==r||N.source!==n)return;let M=N.data;!M||M.type!=="popup-connect"||M.rid!==i||N.ports?.[0]&&(s=N.ports[0],s.start(),s.postMessage({type:"popup-init"}),s.onmessage=z=>{switch(z.data.type){case "popup-complete":u();break;case "popup-error":d(new Error(z.data.error));break;case "popup-closed":{d(new Error("Lost connection with the popup."));break}}},window.removeEventListener("message",g));};window.addEventListener("message",g);}};async function B({privateKey:t,request:e,providerOrigin:n=f,signal:r,device:i,channelId:a}){let o=core.convertBase64StringToJWK(t);if(!o.alg)throw new Error("Property alg in JWK is missing.");let s=await new jose.CompactSign(core.createClientAuthorizationStartRequestChallenge(e)).setProtectedHeader({alg:o.alg}).sign(o),c=await fetch(`${n}/api/startRequest`,{method:"POST",body:JSON.stringify({signature:s,request:e,device:i,channelId:a}),signal:r});if(!c.ok)throw new Error((await c.json()).error);return await c.json()}async function le(t,e=f,n=Ae){let{payload:r}=t.data;if(r.startRequest.data.type!=="message")throw new Error("Invalid request type.");let i=r.startRequest.data.payload,a=core.createMessageChallenge(i,r.client.clientOrigin,r.device.jwk,r.startRequest.rid),{verified:o}=await server.verifyAuthenticationResponse({response:r.authResponse,expectedChallenge:core.bufferToBase64URLString(a),expectedRPID:n,expectedOrigin:e,requireUserVerification:false,credential:{counter:0,id:r.authResponse.id,publicKey:core.convertPubkeyCompressedToCose(r.signer)}});if(!o)throw new Error("WebAuthn message verification failed");let s=r.additionalInfo?.settingsIndexWithAddress;if(!s)throw new Error("User is not delegated");let c=await core.getWalletAddressFromIndex(s.index);return {user:core.UserInfoSchema.parse({publicKey:r.signer,walletAddress:c,settingsIndexWithAddress:s,...r.additionalInfo})}}async function Gf({request:t,privateKey:e,providerOrigin:n,rpId:r,signal:i,device:a,channelId:o}){let s=co__default.default.union([core.StartMessageRequestSchema,core.StartTransactionRequestSchema]).parse(t),{data:c,signer:I,redirectOrigin:_,rid:d}=s;if(c.type==="message"){let A=await B({request:{phase:"start",redirectOrigin:_,signer:I,rid:d,validTill:Date.now()+6e5,data:{type:"message",payload:c.payload}},privateKey:e,providerOrigin:n,signal:i,device:a,channelId:o});return le({data:A.data},n,r)}let u=await B({request:{phase:"start",redirectOrigin:_,signer:I,rid:d,validTill:Date.now()+6e5,data:{type:"transaction",payload:c.payload,sendTx:true,additionalSigners:c.additionalSigners}},providerOrigin:n,privateKey:e,signal:i,device:a,channelId:o});return {txSig:u.data.payload.txSig,user:u.data.payload.user}}
9
- exports.RevibaseProvider=Te;exports.executeTransaction=xo;exports.processClientAuthCallback=Gf;exports.signIn=bo;exports.transferTokens=_f;//# sourceMappingURL=index.cjs.map
8
+ `)}`:e}async function x(t,e,n){let{rid:r,redirectOrigin:i}=t.startRequest(n?.channelId);await new Promise(a=>setTimeout(a,0));let s=e(r,i),o=new AbortController;n?.signal&&(n.signal.aborted?o.abort():n.signal.addEventListener("abort",()=>o.abort())),n?.channelId||t.sendPayloadToProviderViaPopup({rid:r,signal:o.signal}).catch(a=>o.abort(a));let c=n?.channelId?await t.getDeviceSignature(JSON.stringify({rid:r,channelId:n.channelId})):void 0;return t.onClientAuthorizationCallback(s,o.signal,c,n?.channelId)}async function rs(t,e){return x(t,(n,r)=>({phase:"start",rid:n,validTill:Date.now()+6e5,data:{type:"message",payload:xe({domain:r,nonce:v().decode(crypto.getRandomValues(new Uint8Array(16)))})},redirectOrigin:r}),e)}async function ds(t,e,n){let{instructions:r,signer:i,addressesByLookupTableAddress:s,settingsIndexWithAddress:o}=e,c=core.prepareTransactionMessage({payer:w(i.walletAddress),instructions:r,addressesByLookupTableAddress:s}),a=o??i.settingsIndexWithAddress,l=await core.getSettingsFromIndex(a.index),E=(await core.fetchSettingsAccountData(l,a.settingsAddressTreeIndex)).members.some(D=>D.role===core.UserRole.TransactionManager);return x(t,(D,L)=>{let m={transactionMessageBytes:v().decode(c),transactionAddress:l,transactionActionType:E?"execute":"create_with_preauthorized_execution"};return {phase:"start",rid:D,validTill:Date.now()+6e5,data:{type:"transaction",payload:m,sendTx:true,additionalSigners:e.additionalSigners},redirectOrigin:L,signer:i.publicKey}},n)}var te="11111111111111111111111111111111";var Ge=0,He=1,Ve=2,Ke=3,$e=4,Ye=5,Xe=6,Ze=7,qe=8;process.env.NODE_ENV!=="production"&&({[Ge]:"an account with the same address already exists",[Ye]:"provided address does not match addressed derived from seed",[Ke]:"cannot allocate account data of this length",[Ve]:"cannot assign account to this program id",[$e]:"length of requested seed is too long",[Ze]:"stored nonce is still in recent_blockhashes",[Xe]:"advancing stored nonce requires a populated RecentBlockhashes sysvar",[qe]:"specified nonce does not match stored nonce",[He]:"account does not have enough SOL to perform the operation"});var Ie="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";async function Bm(t,e,n){if(e.amount<=0)throw new Error("Transfer amount must be greater than 0");if(!e.destination||typeof e.destination!="string")throw new Error("Destination address is required");let{mint:r,tokenProgram:i=Ie,amount:s,destination:o,signer:c}=e;return x(t,(a,l)=>{let R={transactionActionType:"transfer_intent",transactionAddress:r?i:te,transactionMessageBytes:v().decode(new Uint8Array([...Pe().encode(s),...ue().encode(w(o)),...ue().encode(w(r??te))]))};return {phase:"start",rid:a,validTill:Date.now()+6e5,data:{type:"transaction",payload:R,sendTx:true},redirectOrigin:l,signer:c?.publicKey}},n)}async function _e({privateKey:t,request:e,providerOrigin:n=k,signal:r,device:i,channelId:s}){let o=core.convertBase64StringToJWK(t);if(!o.alg)throw new Error("Property alg in JWK is missing.");let c=await new jose.CompactSign(core.createClientAuthorizationStartRequestChallenge(e)).setProtectedHeader({alg:o.alg}).sign(o),a=await fetch(`${n}/api/startRequest`,{method:"POST",body:JSON.stringify({signature:c,request:e,device:i,channelId:s}),signal:r});if(!a.ok)throw new Error((await a.json()).error);return await a.json()}async function je(t,e=k,n=Fe){let{payload:r}=t.data;if(r.startRequest.data.type!=="message")throw new Error("Invalid request type.");let i=r.startRequest.data.payload,s=core.createMessageChallenge(i,r.client.clientOrigin,r.device.jwk,r.startRequest.rid),{verified:o}=await server.verifyAuthenticationResponse({response:r.authResponse,expectedChallenge:core.bufferToBase64URLString(s),expectedRPID:n,expectedOrigin:e,requireUserVerification:false,credential:{counter:0,id:r.authResponse.id,publicKey:core.convertPubkeyCompressedToCose(r.signer)}});if(!o)throw new Error("WebAuthn message verification failed");return {user:core.UserInfoSchema.parse(r.additionalInfo)}}async function rp({request:t,privateKey:e,providerOrigin:n,rpId:r,signal:i,device:s,channelId:o}){let c=_a__default.default.union([core.StartMessageRequestSchema,core.StartTransactionRequestSchema]).parse(t),{data:a,signer:l,redirectOrigin:R,rid:E}=c,D=Date.now()+6e5;if(a.type==="message"){let m=await _e({request:{phase:"start",redirectOrigin:R,signer:l,rid:E,validTill:D,data:{type:"message",payload:a.payload}},privateKey:e,providerOrigin:n,signal:i,device:s,channelId:o});return je({data:m.data},n,r)}let L=await _e({request:{phase:"start",redirectOrigin:R,signer:l,rid:E,validTill:D,data:{type:"transaction",payload:a.payload,sendTx:true,additionalSigners:a.additionalSigners}},providerOrigin:n,privateKey:e,signal:i,device:s,channelId:o});return {txSig:L.data.payload.txSig,user:L.data.payload.user}}exports.ChannelStatus=qi;exports.RevibaseAbortedError=$;exports.RevibaseAuthError=F;exports.RevibaseEnvironmentError=ee;exports.RevibaseError=f;exports.RevibaseFlowInProgressError=J;exports.RevibasePopupBlockedError=j;exports.RevibasePopupClosedError=V;exports.RevibasePopupNotOpenError=Q;exports.RevibaseProvider=We;exports.RevibaseTimeoutError=K;exports.executeTransaction=ds;exports.processClientAuthCallback=rp;exports.signIn=rs;exports.transferTokens=Bm;//# sourceMappingURL=index.cjs.map
10
9
  //# sourceMappingURL=index.cjs.map