@revibase/lite 0.0.43 → 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,21 +1,33 @@
1
1
  # @revibase/lite
2
2
 
3
- Passkey-based Solana wallet: sign in and approve transactions in a popup; backend authorizes with a server-side private key.
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. **Keys & config** — Get public/private key at [developers.revibase.com](https://developers.revibase.com). Add `/.well-known/revibase.json` with `clientJwk` (your public key), `title`, `description`.
12
- 2. **Backend** — Set `PRIVATE_KEY`. POST route: parse `{ request, device, channelId }` from body, call `processClientAuthCallback({ request, privateKey: process.env.PRIVATE_KEY!, signal: req.signal, device, channelId })`, return JSON.
13
- 3. **Frontend** — Default callback POSTs to `/api/clientAuthorization`. If your path differs, pass a custom callback as 2nd arg to `RevibaseProvider`.
9
+ **API** — Frontend: `RevibaseProvider`, `signIn`, `transferTokens`, `executeTransaction`. Backend: `processClientAuthCallback`. Types: `UserInfo`, `ChannelStatus`, `AuthorizationFlowOptions`, `RevibaseProviderOptions`. Errors: `RevibaseError` + subclasses (`.code`). [AGENTS.md](./AGENTS.md) for automation.
10
+
11
+ ---
12
+
13
+ ## Get started
14
+
15
+ Three steps: keys, backend route, provider.
16
+
17
+ ### 1. Keys
18
+
19
+ Get keys at [developers.revibase.com](https://developers.revibase.com). Add `/.well-known/revibase.json` with `clientJwk`, `title`, `description`.
20
+
21
+ ### 2. Backend
22
+
23
+ Expose **POST** at **`/api/clientAuthorization`** (default). Keep `PRIVATE_KEY` server-only; HTTPS in production.
24
+
25
+ Example handler:
14
26
 
15
27
  ```ts
16
28
  import {
17
- type DeviceSignature,
18
29
  processClientAuthCallback,
30
+ type DeviceSignature,
19
31
  type StartMessageRequest,
20
32
  type StartTransactionRequest,
21
33
  } from "@revibase/lite";
@@ -34,35 +46,120 @@ export async function POST(req: Request) {
34
46
  device,
35
47
  channelId,
36
48
  });
37
- return new Response(JSON.stringify(result));
49
+ return Response.json(result);
38
50
  } catch (e) {
39
- return new Response(JSON.stringify({ error: e instanceof Error ? e.message : String(e) }), { status: 500 });
51
+ const msg = e instanceof Error ? e.message : String(e);
52
+ return Response.json({ error: msg }, { status: 500 });
40
53
  }
41
54
  }
42
55
  ```
43
56
 
57
+ ### 3. Frontend
58
+
59
+ Create a provider. For `executeTransaction`, pass `rpcEndpoint` in options:
60
+
44
61
  ```ts
45
- import { RevibaseProvider, signIn, transferTokens } from "@revibase/lite";
62
+ import {
63
+ RevibaseProvider,
64
+ signIn,
65
+ transferTokens,
66
+ executeTransaction,
67
+ } from "@revibase/lite";
46
68
 
47
69
  const provider = new RevibaseProvider();
48
70
  const { user } = await signIn(provider);
49
- const { txSig } = await transferTokens(provider, { amount: BigInt(100_000_000), destination: "ADDRESS", signer: user });
71
+ const { txSig } = await transferTokens(provider, {
72
+ amount: BigInt(100_000_000),
73
+ destination: "ADDRESS",
74
+ signer: user, // optional for transfers
75
+ });
50
76
  ```
51
77
 
52
- **Custom callback:** `new RevibaseProvider(undefined, async (request, signal, device, channelId) => { const res = await fetch("/api/your-route", { method: "POST", body: JSON.stringify({ request, device, channelId }), signal }); const data = await res.json(); if (!res.ok) throw new Error(data?.error ?? "Authorization failed"); return data; })`
78
+ **Custom instructions** Build instructions with `gill` (Solana instruction builder) or similar, then pass to `executeTransaction`.
79
+
80
+ ```ts
81
+ import { RevibaseProvider, signIn, executeTransaction } from "@revibase/lite";
82
+ import { address, createNoopSigner } from "gill";
83
+ import { getTransferSolInstruction } from "gill/programs";
84
+
85
+ const provider = new RevibaseProvider({
86
+ rpcEndpoint: "https://api.mainnet-beta.solana.com",
87
+ });
88
+ const { user } = await signIn(provider);
53
89
 
54
- **Device binding (no popup):** `const { channelId, url } = await provider.createChannel();` — open `url` in a tab. Then `signIn(provider, { channelId })`, `transferTokens(provider, args, { channelId })`, etc. `subscribeToChannelStatus(listener)`, `closeChannel(channelId)` / `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
+ });
100
+ ```
55
101
 
56
- **Security:** Keep `PRIVATE_KEY` server-only; use HTTPS in production.
102
+ Default: auth in popup. For auth on another device, use a channel (below).
57
103
 
58
104
  ---
59
105
 
60
- ## API
106
+ ## Auth on another device (channel)
107
+
108
+ Channel: auth on another device; requests go there. `createChannel()` → open `url` on that device:
61
109
 
62
- **Client:** `signIn(provider, options?)` → `{ user }`. `transferTokens(provider, args, options?)` → `{ txSig?, user }`. `executeTransaction(provider, args, options?)` → `{ txSig?, user }`. Options: `{ signal?: AbortSignal, channelId?: string }` (type: `AuthorizationFlowOptions`).
110
+ ```ts
111
+ const { channelId, url } = await provider.createChannel();
112
+ ```
63
113
 
64
- **Provider:** `new RevibaseProvider(providerOrigin?, onClientAuthorizationCallback?, logger?)`. Methods: `createChannel()` → `{ channelId, url }`, `subscribeToChannelStatus(listener)` → unsubscribe fn, `cancelChannelRequest(channelId)`, `closeChannel(channelId)`, `closeAllChannels()`. Channel status: `ChannelStatus` enum, `ChannelStatusEntry`.
114
+ ```ts
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 })
122
+ ```
65
123
 
66
- **Server:** `processClientAuthCallback({ request, signal, privateKey, device?, channelId?, providerOrigin?, rpId? })` `{ user }` or `{ txSig?, user }`. Pass `req.signal` so fetches cancel on client disconnect.
124
+ Use `subscribeToChannelStatus` to check channel status.
67
125
 
68
- **Errors:** `RevibaseError` base; `RevibasePopupBlockedError`, `RevibasePopupClosedError`, `RevibaseTimeoutError`, `RevibaseFlowInProgressError`, `RevibaseAbortedError`, `RevibaseAuthError`, `RevibaseEnvironmentError`, `RevibasePopupNotOpenError`. All have `.code` (e.g. `"POPUP_BLOCKED"`, `"TIMEOUT"`).
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
+ ```
150
+
151
+ ### Reconnect
152
+
153
+ If the channel connection is lost, call `reconnectChannel(channelId)`:
154
+
155
+ ```ts
156
+ provider.reconnectChannel(channelId);
157
+ ```
158
+
159
+ ### Cleanup
160
+
161
+ ```ts
162
+ provider.closeChannel(channelId);
163
+ // or
164
+ provider.closeAllChannels();
165
+ ```
package/dist/index.cjs CHANGED
@@ -1,10 +1,9 @@
1
- 'use strict';var core=require('@revibase/core'),jose=require('jose'),sa=require('zod'),server=require('@simplewebauthn/server');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var sa__default=/*#__PURE__*/_interopDefault(sa);var nt=1,rt=2,ot=3,it=4,at=5,st=6,ct=7,dt=8,ut=9,It=10,_t=-32700,At=-32603,Et=-32602,lt=-32601,Rt=-32600,Tt=-32019,Dt=-32018,gt=-32017,Nt=-32016,Ct=-32015,St=-32014,Ot=-32013,ft=-32012,mt=-32011,pt=-32010,ht=-32009,Mt=-32008,yt=-32007,Lt=-32006,Ut=-32005,vt=-32004,Pt=-32003,bt=-32002,Ft=-32001,oe=28e5,ie=2800001,Bt=2800002,Te=2800003,De=2800004,ge=2800005,Ne=2800006,Ce=2800007,Se=2800008,Oe=2800009,fe=2800010,me=2800011,zt=323e4,wt=32300001,kt=3230002,Wt=3230003,xt=3230004,Gt=361e4,Ht=3610001,Vt=3610002,Kt=3610003,$t=3610004,Yt=3610005,Xt=3610006,Zt=3610007,qt=3611e3,jt=3704e3,Jt=3704001,Qt=3704002,en=3704003,tn=3704004,nn=4128e3,rn=4128001,on=4128002,an=4615e3,sn=4615001,cn=4615002,dn=4615003,un=4615004,In=4615005,_n=4615006,An=4615007,En=4615008,ln=4615009,Rn=4615010,Tn=4615011,Dn=4615012,gn=4615013,Nn=4615014,Cn=4615015,Sn=4615016,On=4615017,fn=4615018,mn=4615019,pn=4615020,hn=4615021,Mn=4615022,yn=4615023,Ln=4615024,Un=4615025,vn=4615026,Pn=4615027,bn=4615028,Fn=4615029,Bn=4615030,zn=4615031,wn=4615032,kn=4615033,Wn=4615034,xn=4615035,Gn=4615036,Hn=4615037,Vn=4615038,Kn=4615039,$n=4615040,Yn=4615041,Xn=4615042,Zn=4615043,qn=4615044,jn=4615045,Jn=4615046,Qn=4615047,er=4615048,tr=4615049,nr=4615050,rr=4615051,or=4615052,ir=4615053,ar=4615054,sr=5508e3,cr=5508001,dr=5508002,ur=5508003,Ir=5508004,_r=5508005,Ar=5508006,Er=5508007,lr=5508008,Rr=5508009,Tr=5508010,Dr=5508011,gr=5663e3,Nr=5663001,Cr=5663002,Sr=5663003,Or=5663004,fr=5663005,mr=5663006,pr=5663007,hr=5663008,Mr=5663009,yr=5663010,Lr=5663011,Ur=5663012,vr=5663013,Pr=5663014,br=5663015,Fr=5663016,Br=5663017,zr=5663018,wr=5663019,kr=5663020,Wr=5663021,xr=5663022,Gr=705e4,Hr=7050001,Vr=7050002,Kr=7050003,$r=7050004,Yr=7050005,Xr=7050006,Zr=7050007,qr=7050008,jr=7050009,Jr=7050010,Qr=7050011,eo=7050012,to=7050013,no=7050014,ro=7050015,oo=7050016,io=7050017,ao=7050018,so=7050019,co=7050020,uo=7050021,Io=7050022,_o=7050023,Ao=7050024,Eo=7050025,lo=7050026,Ro=7050027,To=7050028,Do=7050029,go=7050030,No=7050031,Co=7050032,So=7050033,Oo=7050034,fo=7050035,mo=7050036,po=7618e3,ho=7618001,Mo=7618002,yo=7618003,Lo=8078e3,Uo=8078001,vo=8078002,Po=8078003,bo=8078004,Fo=8078005,Bo=8078006,zo=8078007,wo=8078008,ko=8078009,Wo=8078010,ae=8078011,se=8078012,xo=8078013,Go=8078014,Ho=8078015,Vo=8078016,Ko=8078017,$o=8078018,Yo=8078019,Xo=8078020,Zo=8078021,qo=8078022,jo=8078023,Jo=81e5,Qo=8100001,ei=8100002,ti=8100003,ni=819e4,ri=8190001,oi=8190002,ii=8190003,ai=8190004,si=99e5,ci=9900001,di=9900002,ui=9900003,Ii=9900004,_i=9900005,Ai=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 Ei([t,e]){return `${t}=${pe(e)}`}function li(t){let e=Object.entries(t).map(Ei).join("&");return Buffer.from(e,"utf8").toString("base64")}var Ri={[zt]:"Account not found at address: $address",[xt]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[Wt]:"Expected decoded account at address: $address",[kt]:"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.",[Bt]:"$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.",[it]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[nt]:"The network has progressed past the last block for which this transaction could have been committed.",[Lo]:"Codec [$codecDescription] cannot decode empty byte arrays.",[qo]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[Xo]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Fo]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[Bo]:"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.",[vo]:"Expected a fixed-size codec, got a variable-size one.",[xo]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Po]:"Expected a variable-size codec, got a fixed-size one.",[Yo]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[Uo]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[$o]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[ko]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[Wo]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Ho]:"Invalid literal union variant. Expected one of [$variants], got $value.",[zo]:"Expected [$codecDescription] to have $expected items, got $actual.",[se]:"Invalid value $value for base $base with alphabet $alphabet.",[Vo]:"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.",[Go]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[Zo]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[Ko]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[jo]:"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?",[qt]:"No random values implementation could be found.",[ln]:"instruction requires an uninitialized account",[yn]:"instruction tries to borrow reference for an account which is already borrowed",[Ln]:"instruction left account with an outstanding borrowed reference",[hn]:"program other than the account's owner changed the size of the account data",[In]:"account data too small for instruction",[Mn]:"instruction expected an executable account",[Jn]:"An account does not have enough lamports to be rent-exempt",[er]:"Program arithmetic overflowed",[jn]:"Failed to serialize or deserialize account data: $encodedData",[ar]:"Builtin programs must consume compute units",[wn]:"Cross-program invocation call depth too deep",[Vn]:"Computational budget exceeded",[vn]:"custom program error: #$code",[On]:"instruction contains duplicate accounts",[Un]:"instruction modifications of multiply-passed account differ",[Bn]:"executable accounts must be rent exempt",[bn]:"instruction changed executable accounts data",[Fn]:"instruction changed the balance of an executable account",[fn]:"instruction changed executable bit of an account",[Nn]:"instruction modified data of an account it does not own",[gn]:"instruction spent from the balance of an account it does not own",[sn]:"generic instruction error",[nr]:"Provided owner is not allowed",[Zn]:"Account is immutable",[qn]:"Incorrect authority provided",[An]:"incorrect program id for instruction",[_n]:"insufficient funds for instruction",[un]:"invalid account data for instruction",[Qn]:"Invalid account owner",[cn]:"invalid program argument",[Pn]:"program returned invalid error code",[dn]:"invalid instruction data",[Hn]:"Failed to reallocate account data",[Gn]:"Provided seeds do not result in a valid address",[rr]:"Accounts data allocations exceeded the maximum allowed per transaction",[or]:"Max accounts exceeded",[ir]:"Max instruction trace length exceeded",[xn]:"Length of the seed is too long for address generation",[kn]:"An account required by the instruction is missing",[En]:"missing required signature for instruction",[Dn]:"instruction illegally modified the program id of an account",[pn]:"insufficient account keys for instruction",[Kn]:"Cross-program invocation with unauthorized signer or writable account",[$n]:"Failed to create program execution environment",[Xn]:"Program failed to compile",[Yn]:"Program failed to complete",[Sn]:"instruction modified data of a read-only account",[Cn]:"instruction changed the balance of a read-only account",[Wn]:"Cross-program invocation reentrancy not allowed for this instruction",[mn]:"instruction modified rent epoch of an account",[Tn]:"sum of account balances before and after instruction do not match",[Rn]:"instruction requires an initialized account",[an]:"",[zn]:"Unsupported program id",[tr]:"Unsupported sysvar",[_i]:"Invalid instruction plan kind: $kind.",[Mo]:"The provided instruction plan is empty.",[yo]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute and the `cause` error for more details.",[po]:"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).",[Ai]:"Invalid transaction plan kind: $kind.",[ho]:"No more instructions to pack; the message packer has completed the instruction plan.",[nn]:"The instruction does not have any accounts.",[rn]:"The instruction does not have any data.",[on]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[at]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[rt]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[di]:"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",[Ii]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[ci]:"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",[si]:"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",[ui]:"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",[At]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Et]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[Rt]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[lt]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[_t]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[ft]:"$__serverMessage",[Ft]:"$__serverMessage",[vt]:"$__serverMessage",[St]:"$__serverMessage",[gt]:"Epoch rewards period still active at slot $slot",[pt]:"$__serverMessage",[ht]:"$__serverMessage",[Tt]:"Failed to query long-term storage; please try again",[Nt]:"Minimum context slot has not been reached",[Ut]:"Node is unhealthy; behind by $numSlotsBehind slots",[Mt]:"No snapshot",[bt]:"Transaction simulation failed",[Dt]:"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",[yt]:"$__serverMessage",[mt]:"Transaction history is not available from this node",[Lt]:"$__serverMessage",[Ot]:"Transaction signature length mismatch",[Pt]:"Transaction signature verification failure",[Ct]:"$__serverMessage",[jt]:"Key pair bytes must be of length 64, got $byteLength.",[Jt]:"Expected private key bytes with length 32. Actual length: $actualLength.",[Qt]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[tn]:"The provided private key does not match the provided public key.",[en]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[st]:"Lamports value must be in the range [0, 2e64-1]",[ct]:"`$value` cannot be parsed as a `BigInt`",[It]:"$message",[dt]:"`$value` cannot be parsed as a `Number`",[ot]:"No nonce account could be found at address `$nonceAccountAddress`",[ni]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[oi]:"WebSocket was closed before payload could be added to the send buffer",[ii]:"WebSocket connection closed",[ai]:"WebSocket failed to connect",[ri]:"Failed to obtain a subscription id from the server",[ti]:"Could not find an API plan for RPC method: `$method`",[Jo]:"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`.",[ei]:"HTTP error ($statusCode): $message",[Qo]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[sr]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[cr]:"The provided value does not implement the `KeyPairSigner` interface",[ur]:"The provided value does not implement the `MessageModifyingSigner` interface",[Ir]:"The provided value does not implement the `MessagePartialSigner` interface",[dr]:"The provided value does not implement any of the `MessageSigner` interfaces",[Ar]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Er]:"The provided value does not implement the `TransactionPartialSigner` interface",[lr]:"The provided value does not implement the `TransactionSendingSigner` interface",[_r]:"The provided value does not implement any of the `TransactionSigner` interfaces",[Rr]:"More than one `TransactionSendingSigner` was identified.",[Tr]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Dr]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[Zt]:"Cannot export a non-extractable key.",[Ht]:"No digest implementation could be found.",[Gt]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[Vt]:`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.`,[Kt]:"No signature verification implementation could be found.",[$t]:"No key generation implementation could be found.",[Yt]:"No signing implementation could be found.",[Xt]:"No key export implementation could be found.",[ut]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[oo]:"Transaction processing left an account with an outstanding borrowed reference",[Hr]:"Account in use",[Vr]:"Account loaded twice",[Kr]:"Attempt to debit an account but found no record of a prior credit.",[_o]:"Transaction loads an address table account that doesn't exist",[Zr]:"This transaction has already been processed",[qr]:"Blockhash not found",[jr]:"Loader call chain is too deep",[ro]:"Transactions are currently disabled due to cluster maintenance",[go]:"Transaction contains a duplicate instruction ($index) that is not allowed",[Yr]:"Insufficient funds for fee",[No]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[Xr]:"This account may not be used to pay transaction fees",[Qr]:"Transaction contains an invalid account reference",[Eo]:"Transaction loads an address table account with invalid data",[lo]:"Transaction address table lookup uses an invalid index",[Ao]:"Transaction loads an address table account with an invalid owner",[So]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[to]:"This program may not be used for executing instructions",[Ro]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[so]:"Transaction loads a writable account that cannot be written",[Co]:"Transaction exceeded max loaded accounts data size cap",[Jr]:"Transaction requires a fee but has no signature present",[$r]:"Attempt to load a program that does not exist",[fo]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[Oo]:"ResanitizationNeeded",[no]:"Transaction failed to sanitize accounts offsets correctly",[eo]:"Transaction did not pass signature verification",[Io]:"Transaction locked too many accounts",[mo]:"Sum of account balances before and after transaction do not match",[Gr]:"The transaction failed with the error `$errorName`",[ao]:"Transaction version is unsupported",[uo]:"Transaction would exceed account data limit within the block",[Do]:"Transaction would exceed total account data limit",[co]:"Transaction would exceed max account limit within the block",[io]:"Transaction would exceed max Block Cost Limit",[To]:"Transaction would exceed max Vote Cost Limit",[br]:"Attempted to sign a transaction with an address that is not a signer for it",[yr]:"Transaction is missing an address at index: $index.",[Fr]:"Transaction has no expected signers therefore it cannot be encoded",[kr]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[Cr]:"Transaction does not have a blockhash lifetime",[Sr]:"Transaction is not a durable nonce transaction",[fr]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[mr]:"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",[hr]:"No fee payer set in CompiledTransaction",[pr]:"Could not find program address at index $index",[zr]:"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",[Lr]:"Transaction is missing a fee payer.",[Ur]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Pr]:"Transaction first instruction is not advance nonce account instruction.",[vr]:"Transaction with no instructions cannot be durable nonce transaction.",[gr]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Nr]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Br]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Mr]:"Transaction is missing signatures for addresses: $addresses.",[Or]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[Wr]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[xr]:"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",S="t";function Ti(t,e={}){let n=Ri[t];if(n.length===0)return "";let r;function i(o){if(r[S]===2){let s=n.slice(r[h]+1,o);a.push(s in e?`${e[s]}`:`$${s}`);}else r[S]===1&&a.push(n.slice(r[h],o));}let a=[];return n.split("").forEach((o,s)=>{if(s===0){r={[h]:0,[S]:n[0]==="\\"?0:n[0]==="$"?2:1};return}let c;switch(r[S]){case 0:c={[h]:s,[S]:1};break;case 1:o==="\\"?c={[h]:s,[S]:0}:o==="$"&&(c={[h]:s,[S]:2});break;case 2:o==="\\"?c={[h]:s,[S]:0}:o==="$"?c={[h]:s,[S]:2}:o.match(/\w/)||(c={[h]:s,[S]:1});break}c&&(r!==c&&i(s),r=c);}),i(),a.join("")}function Di(t,e={}){if(process.env.NODE_ENV!=="production")return Ti(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 U=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=Di(t,n);super(i,r),this.context=n===void 0?{}:n,this.context.__code=t,this.name="SolanaError";}};function gi(t,e){return "fixedSize"in e?e.fixedSize:e.getSizeFromValue(t)}function B(t){return Object.freeze({...t,encode:e=>{let n=new Uint8Array(gi(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 Ni(t){return "fixedSize"in t&&typeof t.fixedSize=="number"}function Ci(t){return !Ni(t)}function he(t,e){return B({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 Me(t,e){return B({...Ci(t)?{...t,getSizeFromValue:n=>t.getSizeFromValue(e(n))}:t,write:(n,r,i)=>t.write(e(n),r,i)})}function Si(t,e,n=e){if(!e.match(new RegExp(`^[${t}]*$`)))throw new U(se,{alphabet:t,base:t.length,value:n})}var Oi=t=>B({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(Si(t,e),e==="")return r;let[i,a]=ye(e,t[0]);if(!a)return n.set(new Uint8Array(i.length).fill(0),r),r+i.length;let o=Le(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 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 fi="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ve=()=>Oi(fi);var y=()=>ce({read:(t,e=0)=>[Buffer.from(t,e).toString("base64"),t.length]});var de;function Pe(){return de||(de=ve()),de}function mi(t){if(t.length<32||t.length>44)throw new U(ie,{actualLength:t.length});let r=Pe().encode(t).byteLength;if(r!==32)throw new U(oe,{actualLength:r})}function z(t){return mi(t),t}function ue(){return Me(he(Pe(),32),t=>z(t))}function pi(t,e,n,r){if(r<e||r>n)throw new U(ae,{codecDescription:t,max:n,min:e,value:r})}function hi(t){return t?.endian!==1}function Mi(t){return B({fixedSize:t.size,write(e,n,r){t.range&&pi(t.name,t.range[0],t.range[1],e);let i=new ArrayBuffer(t.size);return t.set(new DataView(i),e,hi(t.config)),n.set(new Uint8Array(i),r),r+t.size}})}var be=(t={})=>Mi({config:t,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,n,r)=>e.setBigUint64(0,BigInt(n),r),size:8});function Fe(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 l=window.screenLeft??window.screenX??0,R=window.screenTop??window.screenY??0,E=window.innerWidth??document.documentElement.clientWidth??window.screen.width,f=window.innerHeight??document.documentElement.clientHeight??window.screen.height;i=500,a=600,s=Math.round(l+(E-i)/2),o=Math.round(R+(f-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 Be(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 w(t,e,n){let{rid:r,redirectOrigin:i}=t.startRequest(n?.channelId);await new Promise(c=>setTimeout(c,0));let a=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(c=>o.abort(c));let s=n?.channelId?await t.getDeviceSignature(JSON.stringify({rid:r,channelId:n.channelId})):void 0;return t.onClientAuthorizationCallback(a,o.signal,s,n?.channelId)}async function Fa(t,e){return w(t,(n,r)=>({phase:"start",rid:n,validTill:Date.now()+6e5,data:{type:"message",payload:Be({domain:r,nonce:y().decode(crypto.getRandomValues(new Uint8Array(16)))})},redirectOrigin:r}),e)}async function xa(t,e,n){let{instructions:r,signer:i,addressesByLookupTableAddress:a,hasTxManager:o=true}=e,s=core.prepareTransactionMessage({payer:z(i.walletAddress),instructions:r,addressesByLookupTableAddress:a}),c=await core.getSettingsFromIndex(i.settingsIndexWithAddress.index);return w(t,(l,R)=>{let E={transactionMessageBytes:y().decode(s),transactionAddress:c,transactionActionType:o?"execute":"create_with_preauthorized_execution"};return {phase:"start",rid:l,validTill:Date.now()+6e5,data:{type:"transaction",payload:E,sendTx:true,additionalSigners:e.additionalSigners},redirectOrigin:R,signer:i.publicKey}},n)}var j="11111111111111111111111111111111";var ze=0,we=1,ke=2,We=3,xe=4,Ge=5,He=6,Ve=7,Ke=8;process.env.NODE_ENV!=="production"&&({[ze]:"an account with the same address already exists",[Ge]:"provided address does not match addressed derived from seed",[We]:"cannot allocate account data of this length",[ke]:"cannot assign account to this program id",[xe]:"length of requested seed is too long",[Ve]:"stored nonce is still in recent_blockhashes",[He]:"advancing stored nonce requires a populated RecentBlockhashes sysvar",[Ke]:"specified nonce does not match stored nonce",[we]:"account does not have enough SOL to perform the operation"});var Ie="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";async function Em(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:a,destination:o,signer:s}=e;return w(t,(c,l)=>{let R={transactionActionType:"transfer_intent",transactionAddress:r?i:j,transactionMessageBytes:y().decode(new Uint8Array([...be().encode(a),...ue().encode(z(o)),...ue().encode(z(r??j))]))};return {phase:"start",rid:c,validTill:Date.now()+6e5,data:{type:"transaction",payload:R,sendTx:true},redirectOrigin:l,signer:s?.publicKey}},n)}var k="https://auth.revibase.com";var $e="revibase.com";var O=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 O{constructor(e="Popup blocked. Please enable popups."){super(e,"POPUP_BLOCKED"),this.name="RevibasePopupBlockedError",Object.setPrototypeOf(this,t.prototype);}},V=class t extends O{constructor(e="Popup was closed by the user"){super(e,"POPUP_CLOSED"),this.name="RevibasePopupClosedError",Object.setPrototypeOf(this,t.prototype);}},K=class t extends O{constructor(e="Authentication timed out"){super(e,"TIMEOUT"),this.name="RevibaseTimeoutError",Object.setPrototypeOf(this,t.prototype);}},Q=class t extends O{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 O{constructor(e="Aborted"){super(e,"ABORTED"),this.name="RevibaseAbortedError",Object.setPrototypeOf(this,t.prototype);}},ee=class t extends O{constructor(e="Popup is not open. Call startRequest first."){super(e,"POPUP_NOT_OPEN"),this.name="RevibasePopupNotOpenError",Object.setPrototypeOf(this,t.prototype);}},v=class t extends O{constructor(e){super(e,"AUTH_FAILED"),this.name="RevibaseAuthError",Object.setPrototypeOf(this,t.prototype);}},te=class t extends O{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",Ye="private-key",Xe="public-key",P=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,a)=>{let o=r.transaction(W,"readwrite");o.objectStore(W).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(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(Ye,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(Xe,r),r}static async getOrCreateDevicePublickey(){let e=await t.loadFromDB(Xe);return e||(e=await t.create()),{publicKey:e}}static async sign(e){let n=await t.loadFromDB(Ye);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 Fi=3,Bi=1e3,zi=1e4,wi=3e4,ki=1e4,Wi=64*1024,xi=1008,Gi=1009;function Hi(t,e){return typeof t=="string"?new TextEncoder().encode(t).length<=e?t:null:t.byteLength>e?null:new TextDecoder().decode(t)}var Vi=sa.z.object({event:sa.z.literal("awaiting_recipient")}),Ki=sa.z.object({event:sa.z.literal("recipient_connected"),data:sa.z.object({devicePublicKey:sa.z.string()})}),$i=sa.z.discriminatedUnion("event",[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 Ze(t){let{providerOrigin:e,channelId:n,getDevicePayload:r,callbacks:i,maxReconnectAttempts:a=Fi,reconnectBaseDelayMs:o=Bi,authTimeoutMs:s=zi,maxMessageBytes:c=Wi,verboseLogging:l=false,heartbeatIntervalMs:R=wi,heartbeatTimeoutMs:E=ki}=t,{onAwaitingRecipient:f,onRecipientConnected:F,onClose:g,onError:T,onConnectionLost:x,onConnected:Y}=i,Ae=new URL(e),Je=Ae.protocol==="https:"?"wss:":"ws:",Qe=Ae.host,ne=`${Je}//${Qe}/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,D=false,m=0,G=null,X=null,p=null,L=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,D=false,Z(),q();try{(A.readyState===WebSocket.OPEN||A.readyState===WebSocket.CONNECTING)&&A.close(u??1e3,d??"Closed");}catch{}}}async function et(u){let d,N=new Promise((C,H)=>{d=setTimeout(()=>H(new Error("Auth timeout")),s);});try{return await Promise.race([r(u),N])}finally{d!=null&&clearTimeout(d);}}function tt(u,d,N){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,N??"Reconnecting");}catch{}}function le(){let u=A;A=new WebSocket(ne),Re(A),tt(u,1e3,"Reconnecting");}function Re(u){u.onopen=async()=>{if(!_){I.info("[Channel WS Sender] Socket opened",{channelId:n});try{let d=await et(n);if(_||u.readyState!==WebSocket.OPEN)return;u.send(JSON.stringify({type:"auth",device:d})),I.info("[Channel WS Sender] Auth sent",{channelId:n}),m=0,Y?.(),R>0&&E>0&&(X=setInterval(()=>{if(!(_||A.readyState!==WebSocket.OPEN)){if(p!=null){I.warn("[Channel WS Sender] Heartbeat timeout",{channelId:n}),L=!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}),L=!0,q();try{A.close(1e3,"Heartbeat timeout");}catch{}}},E);}},R));}catch(d){I.error("Channel WebSocket (sender) auth failed",d,{channelId:n}),T?.("Auth failed"),Ee(xi,"Auth failed");}}},u.onmessage=d=>{if(_)return;let N=Hi(d.data,c);if(N===null){I.warn("[Channel WS Sender] Message too large or invalid",{channelId:n}),re=true,Z();try{u.close(Gi,"Message too large");}catch{}return}try{if(JSON.parse(N)?.event==="pong"){p!=null&&(clearTimeout(p),p=null);return}}catch{}let C=Yi(N);if(!C){l&&I.info("[Channel WS Sender] Unparseable message",{channelId:n,preview:N.slice(0,100)});return}l&&I.info("[Channel WS Sender] Message received",{channelId:n,event:C.event,...C.event!=="awaiting_recipient"&&{data:C.data}}),C.event==="awaiting_recipient"?f?.():C.event==="recipient_connected"&&F?.(C.data);},u.onclose=d=>{if(q(),d.target!==A)return;if(_&&!L){g?.({code:d.code,reason:d.reason||"",wasClean:d.wasClean});return}if(L?I.info("[Channel WS Sender] Socket closed (heartbeat timeout)",{channelId:n,code:d.code,reason:d.reason||"(none)",retryCount:m}):_||I.info("[Channel WS Sender] Socket closed",{channelId:n,code:d.code,reason:d.reason||"(none)",wasClean:d.wasClean,retryCount:m}),re){_=true,g?.({code:d.code,reason:d.reason||"",wasClean:d.wasClean});return}if(d.wasClean&&!L){_=true,g?.({code:d.code,reason:d.reason||"",wasClean:d.wasClean});return}if(L&&(L=false),m>=a){_=true,D=true,I.info("[Channel WS Sender] Max reconnect attempts reached",{channelId:n,maxReconnectAttempts:a}),x?.();return}let N=o*Math.pow(2,m),C=.8+.4*Math.random(),H=Math.min(Math.round(N*C),3e4);m+=1,I.info("[Channel WS Sender] Scheduling reconnect",{channelId:n,attempt:m,delayMs:H}),G=setTimeout(()=>{G=null,!_&&(I.info("[Channel WS Sender] Reconnecting",{channelId:n,attempt:m}),le());},H);},u.onerror=()=>{I.info("[Channel WS Sender] Socket error",{channelId:n}),_||T?.("Connection error");};}return Re(A),{reconnect(){return _||!D?(I.info("[Channel WS Sender] reconnect() no-op",{channelId:n,closed:_,connectionLost:D}),false):(I.info("[Channel WS Sender] reconnect() starting",{channelId:n}),D=false,m=0,Z(),le(),true)},closeChannel(){if(!_&&!D&&A.readyState===WebSocket.OPEN)try{I.info("[Channel WS] Sending close",{channelId:n}),A.send(JSON.stringify({type:"close"}));}catch(u){I.error("Channel close send failed",u,{channelId:n}),T?.("Failed to close channel");}else _||I.info("[Channel WS] closeChannelAndConnection() skip send",{channelId:n,closed:_,connectionLost:D,readyState:A.readyState});if(!_){if(I.info("[Channel WS] close() called",{channelId:n,connectionLost:D}),D){_=true,D=false,Z(),g?.({code:1e3,reason:"Closed",wasClean:true});return}Ee();}},cancelRequest(){if(_||D||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}),T?.("Failed to cancel request"),false}}}}var Zi=(a=>(a[a.AUTHENTICATING=0]="AUTHENTICATING",a[a.AWAITING_RECIPIENT=1]="AWAITING_RECIPIENT",a[a.RECIPIENT_CONNECTED=2]="RECIPIENT_CONNECTED",a[a.CHANNEL_CLOSED=3]="CHANNEL_CLOSED",a[a.ERROR=4]="ERROR",a))(Zi||{}),qe=class{pending=new Map;onClientAuthorizationCallback;providerOrigin;popUp=null;channelWs=new Map;channelStatusListeners=new Set;logger;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 v(o.error??"Authorization failed");return o};constructor(e,n,r){this.onClientAuthorizationCallback=n??this.defaultCallback,this.providerOrigin=e??k,this.logger=r??{info:()=>{},warn:()=>{},error:()=>{}};}async getDeviceSignature(e){return {jwk:(await P.getOrCreateDevicePublickey()).publicKey,jws:await P.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 c=await e.json();throw new v(c.error??"Unable to generate challenge")}let{id:n,challenge:r}=await e.json(),i={jwk:(await P.getOrCreateDevicePublickey()).publicKey,jws:await P.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 c=await a.json();throw new v(c.error??"Unable to create channel")}let{channelId:o}=await a.json(),s=Ze({channelId:o,getDevicePayload:this.getDeviceSignature,providerOrigin:this.providerOrigin,callbacks:{onAwaitingRecipient:()=>this.setChannelStatus(o,{status:1}),onRecipientConnected:({devicePublicKey:c})=>this.setChannelStatus(o,{status:2,recipient:c}),onClose:()=>{this.setChannelStatus(o,{status:3}),this.channelWs.delete(o);},onError:c=>this.setChannelStatus(o,{status:4,error:c})}});return this.channelWs.set(o,s),this.setChannelStatus(o,{status:0}),{channelId:o,url:`${this.providerOrigin}?channelId=${o}`}}cancelChannelRequest(e){this.channelWs.get(e)?.cancelRequest();}async closeChannel(e){this.channelWs.get(e)?.closeChannel(),this.channelWs.delete(e);}async closeAllChannels(){this.channelWs.entries().forEach(e=>e[1].closeChannel()),this.channelWs.clear();}startRequest(e){let n=window.origin,r=y().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=Fe(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 te;if(this.pending.size>0)throw new Q;return new Promise((i,a)=>{let o=setTimeout(()=>{let s=this.pending.get(e);s&&(s.cancel?s.cancel(new K):(this.pending.delete(e),a(new K)));},n);if(!this.popUp||this.popUp.closed)throw new ee;this.pending.set(e,{rid:e,resolve:i,reject:a,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:a}=e,o=this.pending.get(i);if(!o)return;let s=null,c=false,l=()=>{E(new $);},R=()=>{a.removeEventListener("abort",l),window.removeEventListener("message",g);try{s?.close();}catch{}s=null;try{n&&!n.closed&&n.close();}catch{}this.popUp=null,clearInterval(F);},E=T=>{c||(c=true,clearTimeout(o.timeoutId),this.pending.delete(i),R(),o.reject(T));},f=()=>{c||(c=true,clearTimeout(o.timeoutId),this.pending.delete(i),R(),o.resolve({rid:i}));};if(o.cancel=E,a.aborted){E(new $);return}a.addEventListener("abort",l);let F=setInterval(()=>{n?.closed&&E(new V);},2e3),g=T=>{if(T.origin!==r||T.source!==n)return;let x=T.data;!x||x.type!=="popup-connect"||x.rid!==i||T.ports?.[0]&&(s=T.ports[0],s.start(),s.postMessage({type:"popup-init"}),s.onmessage=Y=>{switch(Y.data.type){case "popup-complete":f();break;case "popup-error":E(new v(Y.data.error));break;case "popup-closed":{E(new V("Lost connection with the popup."));break}}},window.removeEventListener("message",g));};window.addEventListener("message",g);}};async function _e({privateKey:t,request:e,providerOrigin:n=k,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 je(t,e=k,n=$e){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 Zm({request:t,privateKey:e,providerOrigin:n,rpId:r,signal:i,device:a,channelId:o}){let s=sa__default.default.union([core.StartMessageRequestSchema,core.StartTransactionRequestSchema]).parse(t),{data:c,signer:l,redirectOrigin:R,rid:E}=s,f=Date.now()+6e5;if(c.type==="message"){let g=await _e({request:{phase:"start",redirectOrigin:R,signer:l,rid:E,validTill:f,data:{type:"message",payload:c.payload}},privateKey:e,providerOrigin:n,signal:i,device:a,channelId:o});return je({data:g.data},n,r)}let F=await _e({request:{phase:"start",redirectOrigin:R,signer:l,rid:E,validTill:f,data:{type:"transaction",payload:c.payload,sendTx:true,additionalSigners:c.additionalSigners}},providerOrigin:n,privateKey:e,signal:i,device:a,channelId:o});return {txSig:F.data.payload.txSig,user:F.data.payload.user}}
9
- exports.ChannelStatus=Zi;exports.RevibaseAbortedError=$;exports.RevibaseAuthError=v;exports.RevibaseEnvironmentError=te;exports.RevibaseError=O;exports.RevibaseFlowInProgressError=Q;exports.RevibasePopupBlockedError=J;exports.RevibasePopupClosedError=V;exports.RevibasePopupNotOpenError=ee;exports.RevibaseProvider=qe;exports.RevibaseTimeoutError=K;exports.executeTransaction=xa;exports.processClientAuthCallback=Zm;exports.signIn=Fa;exports.transferTokens=Em;//# 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