@revibase/lite 0.0.37 → 0.0.39
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 +75 -70
- package/dist/index.cjs +4 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -12
- package/dist/index.d.ts +9 -12
- package/dist/index.js +4 -6
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,35 +1,16 @@
|
|
|
1
1
|
# @revibase/lite
|
|
2
2
|
|
|
3
|
-
Add **Revibase** (passkey-based Solana wallet) to your app. Users sign in and
|
|
3
|
+
Add **Revibase** (a passkey-based Solana wallet) to your app. Users sign in and approve transactions in a popup, while your backend authorizes requests with a private key that stays server-side.
|
|
4
4
|
|
|
5
|
-
##
|
|
6
|
-
|
|
7
|
-
1. **Frontend** — User triggers sign-in or a transaction; the app opens a Revibase popup and sends the auth request to your backend.
|
|
8
|
-
2. **Backend** — Your POST route calls `processClientAuthCallback` with the request body and your **private key**, talks to the Revibase provider, and returns the result.
|
|
9
|
-
3. **Frontend** — The callback receives the result; the popup closes and your app gets `user` (and optionally `txSig`).
|
|
10
|
-
|
|
11
|
-
The private key is only used on the server. The client only sees the request/result payloads.
|
|
12
|
-
|
|
13
|
-
**Device binding (optional)** — When you pass a `channelId` to the provider, the SDK creates a **device-bound key** (Ed25519, non-exportable) and stores it in the browser’s IndexedDB. That key is used to sign the channel id; your backend receives `device: { jwk, jws }` and can bind the session to that device. The private key never leaves the device and cannot be exported.
|
|
14
|
-
|
|
15
|
-
## Prerequisites
|
|
16
|
-
|
|
17
|
-
Get a single **key pair** from [developers.revibase.com](https://developers.revibase.com). You will use:
|
|
18
|
-
|
|
19
|
-
- **Public key** → in `revibase.json` as `clientJwk`
|
|
20
|
-
- **Private key** → in env as `PRIVATE_KEY` (server-only)
|
|
21
|
-
|
|
22
|
-
## Setup
|
|
23
|
-
|
|
24
|
-
### 1. Install
|
|
5
|
+
## Quick Start
|
|
25
6
|
|
|
26
7
|
```bash
|
|
27
8
|
pnpm add @revibase/lite
|
|
28
9
|
```
|
|
29
10
|
|
|
30
|
-
###
|
|
11
|
+
### 1) Add well-known config
|
|
31
12
|
|
|
32
|
-
|
|
13
|
+
Create `/.well-known/revibase.json` (for example in `public/.well-known/revibase.json`):
|
|
33
14
|
|
|
34
15
|
```json
|
|
35
16
|
{
|
|
@@ -39,9 +20,9 @@ Serve `/.well-known/revibase.json` (e.g. from `public/.well-known/revibase.json`
|
|
|
39
20
|
}
|
|
40
21
|
```
|
|
41
22
|
|
|
42
|
-
###
|
|
23
|
+
### 2) Add backend route
|
|
43
24
|
|
|
44
|
-
Set `PRIVATE_KEY` to
|
|
25
|
+
Set `PRIVATE_KEY` to your matching private key, then forward the client payload to `processClientAuthCallback`:
|
|
45
26
|
|
|
46
27
|
```ts
|
|
47
28
|
import { processClientAuthCallback } from "@revibase/lite";
|
|
@@ -72,70 +53,92 @@ export async function POST(req: Request) {
|
|
|
72
53
|
}
|
|
73
54
|
```
|
|
74
55
|
|
|
75
|
-
###
|
|
76
|
-
|
|
77
|
-
Create a `RevibaseProvider` whose callback POSTs the auth request to your route. Pass the callback’s **`signal`** to `fetch` so that when the popup is closed or the flow aborts, the client request (and thus the server’s `req.signal`) is cancelled.
|
|
78
|
-
|
|
79
|
-
```ts
|
|
80
|
-
import {
|
|
81
|
-
type ClientAuthorizationCallback,
|
|
82
|
-
RevibaseProvider,
|
|
83
|
-
} from "@revibase/lite";
|
|
84
|
-
|
|
85
|
-
const provider = new RevibaseProvider({
|
|
86
|
-
onClientAuthorizationCallback: async (request, signal, device, channelId) => {
|
|
87
|
-
const res = await fetch("/api/clientAuthorization", {
|
|
88
|
-
method: "POST",
|
|
89
|
-
headers: { "Content-Type": "application/json" },
|
|
90
|
-
body: JSON.stringify({ request, device, channelId }),
|
|
91
|
-
signal,
|
|
92
|
-
});
|
|
93
|
-
const data = await res.json();
|
|
94
|
-
if (!res.ok)
|
|
95
|
-
throw new Error(
|
|
96
|
-
(data as { error?: string }).error ?? "Authorization failed",
|
|
97
|
-
);
|
|
98
|
-
return data;
|
|
99
|
-
},
|
|
100
|
-
channelId,
|
|
101
|
-
});
|
|
102
|
-
```
|
|
56
|
+
### 3) Use in frontend
|
|
103
57
|
|
|
104
|
-
|
|
58
|
+
If your backend route is `/api/clientAuthorization`, the default provider is enough:
|
|
105
59
|
|
|
106
60
|
```ts
|
|
107
|
-
import { signIn, transferTokens } from "@revibase/lite";
|
|
61
|
+
import { RevibaseProvider, signIn, transferTokens } from "@revibase/lite";
|
|
108
62
|
|
|
63
|
+
const provider = new RevibaseProvider();
|
|
109
64
|
const { user } = await signIn(provider);
|
|
110
|
-
|
|
111
65
|
const { txSig } = await transferTokens(provider, {
|
|
112
66
|
amount: BigInt(100_000_000),
|
|
113
67
|
destination: "RECIPIENT_ADDRESS",
|
|
114
68
|
signer: user,
|
|
115
|
-
// mint: "..." // optional; omit for SOL
|
|
116
69
|
});
|
|
117
70
|
```
|
|
118
71
|
|
|
119
|
-
|
|
72
|
+
### 4) Optional: custom callback route
|
|
73
|
+
|
|
74
|
+
If your route path is different, pass a custom callback and forward `signal`:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import type { ClientAuthorizationCallback } from "@revibase/lite";
|
|
78
|
+
import { RevibaseProvider } from "@revibase/lite";
|
|
79
|
+
|
|
80
|
+
const onClientAuthorizationCallback: ClientAuthorizationCallback = async (
|
|
81
|
+
request,
|
|
82
|
+
signal,
|
|
83
|
+
device,
|
|
84
|
+
channelId,
|
|
85
|
+
) => {
|
|
86
|
+
const res = await fetch("/api/revibase/authorize", {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: { "Content-Type": "application/json" },
|
|
89
|
+
body: JSON.stringify({ request, device, channelId }),
|
|
90
|
+
signal,
|
|
91
|
+
});
|
|
92
|
+
const data = await res.json();
|
|
93
|
+
if (!res.ok) throw new Error(data?.error ?? "Authorization failed");
|
|
94
|
+
return data;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const provider = new RevibaseProvider(onClientAuthorizationCallback);
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### 5) Optional: device binding
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
provider.setChannelId("session-or-channel-id");
|
|
104
|
+
// ... run auth flows
|
|
105
|
+
await provider.closeChannel();
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## How it works
|
|
109
|
+
|
|
110
|
+
1. **Frontend** opens Revibase popup and sends auth payload to your backend callback.
|
|
111
|
+
2. **Backend** calls `processClientAuthCallback` with `request`, `privateKey`, and `req.signal`.
|
|
112
|
+
3. **Frontend** receives `{ user }` or `{ txSig, user }`.
|
|
113
|
+
|
|
114
|
+
Your private key is server-only. The browser only handles payloads and results.
|
|
115
|
+
|
|
116
|
+
For custom instructions, use `executeTransaction` (see API reference).
|
|
120
117
|
|
|
121
118
|
---
|
|
122
119
|
|
|
123
|
-
**
|
|
120
|
+
**Quick checklist**
|
|
121
|
+
- Install `@revibase/lite`.
|
|
122
|
+
- Add `/.well-known/revibase.json` with `clientJwk`.
|
|
123
|
+
- Set `PRIVATE_KEY` on the server.
|
|
124
|
+
- Add a POST route using `processClientAuthCallback` and pass `req.signal`.
|
|
125
|
+
- Create `RevibaseProvider` and ensure callback `fetch` uses `signal`.
|
|
126
|
+
- Call `signIn(provider)` and/or `transferTokens` / `executeTransaction`.
|
|
124
127
|
|
|
125
|
-
**Security:**
|
|
128
|
+
**Security note:** Keep `PRIVATE_KEY` server-only and use HTTPS in production.
|
|
126
129
|
|
|
127
130
|
---
|
|
128
131
|
|
|
129
132
|
## API Reference
|
|
130
133
|
|
|
131
|
-
|
|
134
|
+
`@revibase/lite` exports browser client helpers, the browser `RevibaseProvider`, server helpers, and shared types.
|
|
132
135
|
|
|
133
136
|
### Client (browser)
|
|
134
137
|
|
|
135
138
|
| Function | Description |
|
|
136
139
|
| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
137
|
-
| **`signIn(provider)`** | Opens the auth popup and returns `{ user: UserInfo }` after
|
|
138
|
-
| **`executeTransaction(provider, args)`** | Builds and executes a transaction
|
|
140
|
+
| **`signIn(provider)`** | Opens the auth popup and returns `{ user: UserInfo }` after passkey auth. |
|
|
141
|
+
| **`executeTransaction(provider, args)`** | Builds and executes a custom transaction. Action type is selected from wallet settings. |
|
|
139
142
|
| **`transferTokens(provider, args)`** | Transfers SOL or SPL tokens. Set `mint` for SPL; omit for native SOL. |
|
|
140
143
|
|
|
141
144
|
**Signatures**
|
|
@@ -168,18 +171,20 @@ function transferTokens(
|
|
|
168
171
|
|
|
169
172
|
### Provider (browser)
|
|
170
173
|
|
|
171
|
-
**`RevibaseProvider`** — Connects your app to the Revibase auth popup and your backend.
|
|
174
|
+
**`RevibaseProvider`** — Connects your app to the Revibase auth popup and your backend route.
|
|
172
175
|
|
|
173
|
-
- **Constructor:** `new RevibaseProvider(
|
|
174
|
-
- `
|
|
175
|
-
- `
|
|
176
|
-
|
|
176
|
+
- **Constructor:** `new RevibaseProvider(onClientAuthorizationCallback?, providerOrigin?)`
|
|
177
|
+
- `onClientAuthorizationCallback` — Optional. Called with `(request, signal, device, channelId)`. POST `request`, `device`, and `channelId` to your backend and return JSON. Pass `signal` to `fetch` for cancellation.
|
|
178
|
+
- `providerOrigin` — Optional. Default `https://auth.revibase.com`.
|
|
179
|
+
- **Methods**
|
|
180
|
+
- `setChannelId(channelId: string): void` — Enables channel-based flows and includes device proof (`device`) + `channelId` in callback payloads.
|
|
181
|
+
- `closeChannel(): Promise<void>` — Closes the active channel on the provider and clears local `channelId`.
|
|
177
182
|
|
|
178
183
|
### Server
|
|
179
184
|
|
|
180
185
|
| Function | Description |
|
|
181
186
|
| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
182
|
-
| **`processClientAuthCallback(options)`** | Validates the start request, calls
|
|
187
|
+
| **`processClientAuthCallback(options)`** | Validates the start request, calls Revibase start + getResult APIs, and returns `{ user }` (message) or `{ txSig, user }` (transaction). Pass `req.signal` to cancel fetches when the client disconnects. |
|
|
183
188
|
| **`createTransactionSigner(request, privateKey)`** | Signs an array of serialized transactions. Use when the provider requires additional signers. |
|
|
184
189
|
|
|
185
190
|
**Signatures**
|
|
@@ -187,7 +192,7 @@ function transferTokens(
|
|
|
187
192
|
```ts
|
|
188
193
|
function processClientAuthCallback(options: {
|
|
189
194
|
request: StartMessageRequest | StartTransactionRequest;
|
|
190
|
-
signal: AbortSignal;
|
|
195
|
+
signal: AbortSignal; // pass req.signal from your POST route
|
|
191
196
|
privateKey: string; // base64-encoded JWK
|
|
192
197
|
device?: DeviceSignature; // { jwk, jws } from device-bound key when channelId is used
|
|
193
198
|
channelId?: string;
|
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,10 @@
|
|
|
1
|
-
'use strict';var core=require('@revibase/core'),jose=require('jose'),Qi=require('zod'),server=require('@simplewebauthn/server');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Qi__default=/*#__PURE__*/_interopDefault(Qi);var pt=1,ht=2,Mt=3,Lt=4,yt=5,Ut=6,bt=7,Ft=8,vt=9,Pt=10,Bt=-32700,zt=-32603,wt=-32602,kt=-32601,xt=-32600,Wt=-32019,Vt=-32018,Gt=-32017,Ht=-32016,Kt=-32015,$t=-32014,Yt=-32013,Xt=-32012,Zt=-32011,jt=-32010,qt=-32009,Jt=-32008,Qt=-32007,en=-32006,tn=-32005,nn=-32004,rn=-32003,on=-32002,an=-32001,G=28e5,H=2800001,sn=2800002,Ie=2800003,_e=2800004,Ae=2800005,le=2800006,Ee=2800007,Re=2800008,Te=2800009,ge=2800010,De=2800011,cn=323e4,un=32300001,dn=3230002,In=3230003,_n=3230004,An=361e4,ln=3610001,En=3610002,Rn=3610003,Tn=3610004,gn=3610005,Dn=3610006,Nn=3610007,Sn=3611e3,Cn=3704e3,On=3704001,fn=3704002,mn=3704003,pn=3704004,hn=4128e3,Mn=4128001,Ln=4128002,yn=4615e3,Un=4615001,bn=4615002,Fn=4615003,vn=4615004,Pn=4615005,Bn=4615006,zn=4615007,wn=4615008,kn=4615009,xn=4615010,Wn=4615011,Vn=4615012,Gn=4615013,Hn=4615014,Kn=4615015,$n=4615016,Yn=4615017,Xn=4615018,Zn=4615019,jn=4615020,qn=4615021,Jn=4615022,Qn=4615023,er=4615024,tr=4615025,nr=4615026,rr=4615027,or=4615028,ir=4615029,ar=4615030,sr=4615031,cr=4615032,ur=4615033,dr=4615034,Ir=4615035,_r=4615036,Ar=4615037,lr=4615038,Er=4615039,Rr=4615040,Tr=4615041,gr=4615042,Dr=4615043,Nr=4615044,Sr=4615045,Cr=4615046,Or=4615047,fr=4615048,mr=4615049,pr=4615050,hr=4615051,Mr=4615052,Lr=4615053,yr=4615054,Ur=5508e3,br=5508001,Fr=5508002,vr=5508003,Pr=5508004,Br=5508005,zr=5508006,wr=5508007,kr=5508008,xr=5508009,Wr=5508010,Vr=5508011,Ne=5663e3,Se=5663001,K=5663002,$=5663003,Ce=5663004,Oe=5663005,fe=5663006,me=5663007,pe=5663008,he=5663009,Gr=5663010,Hr=5663011,Me=5663012,Kr=5663013,$r=5663014,Le=5663015,ye=5663016,Y=5663017,Yr=5663018,Xr=5663019,Ue=5663020,X=5663021,be=5663022,Zr=705e4,jr=7050001,qr=7050002,Jr=7050003,Qr=7050004,eo=7050005,to=7050006,no=7050007,ro=7050008,oo=7050009,io=7050010,ao=7050011,so=7050012,co=7050013,uo=7050014,Io=7050015,_o=7050016,Ao=7050017,lo=7050018,Eo=7050019,Ro=7050020,To=7050021,go=7050022,Do=7050023,No=7050024,So=7050025,Co=7050026,Oo=7050027,fo=7050028,mo=7050029,po=7050030,ho=7050031,Mo=7050032,Lo=7050033,yo=7050034,Uo=7050035,bo=7050036,Fo=7618e3,vo=7618001,Po=7618002,Bo=7618003,Z=8078e3,j=8078001,Fe=8078002,ve=8078003,Pe=8078004,Be=8078005,ze=8078006,zo=8078007,wo=8078008,ko=8078009,xo=8078010,q=8078011,P=8078012,J=8078013,Q=8078014,Wo=8078015,Vo=8078016,Go=8078017,Ho=8078018,Ko=8078019,we=8078020,ke=8078021,$o=8078022,xe=8078023,Yo=81e5,Xo=8100001,Zo=8100002,jo=8100003,qo=819e4,Jo=8190001,Qo=8190002,ei=8190003,ti=8190004,ni=99e5,ri=9900001,oi=9900002,ii=9900003,ai=9900004,si=9900005,ci=9900006;function We(e){return Array.isArray(e)?"%5B"+e.map(We).join("%2C%20")+"%5D":typeof e=="bigint"?`${e}n`:encodeURIComponent(String(e!=null&&Object.getPrototypeOf(e)===null?{...e}:e))}function ui([e,t]){return `${e}=${We(t)}`}function di(e){let t=Object.entries(e).map(ui).join("&");return Buffer.from(t,"utf8").toString("base64")}var Ii={[cn]:"Account not found at address: $address",[_n]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[In]:"Expected decoded account at address: $address",[dn]:"Failed to decode account data at address: $address",[un]:"Accounts not found at addresses: $addresses",[Te]:"Unable to find a viable program address bump seed.",[sn]:"$putativeAddress is not a base58-encoded address.",[G]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[Ie]:"The `CryptoKey` must be an `Ed25519` public key.",[De]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Re]:"Invalid seeds; point must fall off the Ed25519 curve.",[_e]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[le]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[Ee]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[Ae]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[ge]:"Program address cannot end with PDA marker.",[H]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[Lt]:"Expected base58-encoded blockash string of length in the range [32, 44]. Actual length: $actualLength.",[pt]:"The network has progressed past the last block for which this transaction could have been committed.",[Z]:"Codec [$codecDescription] cannot decode empty byte arrays.",[$o]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[we]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Be]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[ze]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[Pe]:"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.",[Fe]:"Expected a fixed-size codec, got a variable-size one.",[J]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[ve]:"Expected a variable-size codec, got a fixed-size one.",[Ko]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[j]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[Ho]:"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.",[xo]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[Wo]:"Invalid literal union variant. Expected one of [$variants], got $value.",[zo]:"Expected [$codecDescription] to have $expected items, got $actual.",[P]:"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.",[q]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Q]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[ke]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[Go]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[xe]:"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?",[Sn]:"No random values implementation could be found.",[kn]:"instruction requires an uninitialized account",[Qn]:"instruction tries to borrow reference for an account which is already borrowed",[er]:"instruction left account with an outstanding borrowed reference",[qn]:"program other than the account's owner changed the size of the account data",[Pn]:"account data too small for instruction",[Jn]:"instruction expected an executable account",[Cr]:"An account does not have enough lamports to be rent-exempt",[fr]:"Program arithmetic overflowed",[Sr]:"Failed to serialize or deserialize account data: $encodedData",[yr]:"Builtin programs must consume compute units",[cr]:"Cross-program invocation call depth too deep",[lr]:"Computational budget exceeded",[nr]:"custom program error: #$code",[Yn]:"instruction contains duplicate accounts",[tr]:"instruction modifications of multiply-passed account differ",[ar]:"executable accounts must be rent exempt",[or]:"instruction changed executable accounts data",[ir]:"instruction changed the balance of an executable account",[Xn]:"instruction changed executable bit of an account",[Hn]:"instruction modified data of an account it does not own",[Gn]:"instruction spent from the balance of an account it does not own",[Un]:"generic instruction error",[pr]:"Provided owner is not allowed",[Dr]:"Account is immutable",[Nr]:"Incorrect authority provided",[zn]:"incorrect program id for instruction",[Bn]:"insufficient funds for instruction",[vn]:"invalid account data for instruction",[Or]:"Invalid account owner",[bn]:"invalid program argument",[rr]:"program returned invalid error code",[Fn]:"invalid instruction data",[Ar]:"Failed to reallocate account data",[_r]:"Provided seeds do not result in a valid address",[hr]:"Accounts data allocations exceeded the maximum allowed per transaction",[Mr]:"Max accounts exceeded",[Lr]:"Max instruction trace length exceeded",[Ir]:"Length of the seed is too long for address generation",[ur]:"An account required by the instruction is missing",[wn]:"missing required signature for instruction",[Vn]:"instruction illegally modified the program id of an account",[jn]:"insufficient account keys for instruction",[Er]:"Cross-program invocation with unauthorized signer or writable account",[Rr]:"Failed to create program execution environment",[gr]:"Program failed to compile",[Tr]:"Program failed to complete",[$n]:"instruction modified data of a read-only account",[Kn]:"instruction changed the balance of a read-only account",[dr]:"Cross-program invocation reentrancy not allowed for this instruction",[Zn]:"instruction modified rent epoch of an account",[Wn]:"sum of account balances before and after instruction do not match",[xn]:"instruction requires an initialized account",[yn]:"",[sr]:"Unsupported program id",[mr]:"Unsupported sysvar",[si]:"Invalid instruction plan kind: $kind.",[Po]:"The provided instruction plan is empty.",[Bo]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute and the `cause` error for more details.",[Fo]:"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).",[ci]:"Invalid transaction plan kind: $kind.",[vo]:"No more instructions to pack; the message packer has completed the instruction plan.",[hn]:"The instruction does not have any accounts.",[Mn]:"The instruction does not have any data.",[Ln]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[yt]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[ht]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[oi]:"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.",[ri]:"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",[ni]:"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",[ii]:"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",[zt]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[wt]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[xt]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[kt]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Bt]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Xt]:"$__serverMessage",[an]:"$__serverMessage",[nn]:"$__serverMessage",[$t]:"$__serverMessage",[Gt]:"Epoch rewards period still active at slot $slot",[jt]:"$__serverMessage",[qt]:"$__serverMessage",[Wt]:"Failed to query long-term storage; please try again",[Ht]:"Minimum context slot has not been reached",[tn]:"Node is unhealthy; behind by $numSlotsBehind slots",[Jt]:"No snapshot",[on]:"Transaction simulation failed",[Vt]:"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",[Qt]:"$__serverMessage",[Zt]:"Transaction history is not available from this node",[en]:"$__serverMessage",[Yt]:"Transaction signature length mismatch",[rn]:"Transaction signature verification failure",[Kt]:"$__serverMessage",[Cn]:"Key pair bytes must be of length 64, got $byteLength.",[On]:"Expected private key bytes with length 32. Actual length: $actualLength.",[fn]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[pn]:"The provided private key does not match the provided public key.",[mn]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[Ut]:"Lamports value must be in the range [0, 2e64-1]",[bt]:"`$value` cannot be parsed as a `BigInt`",[Pt]:"$message",[Ft]:"`$value` cannot be parsed as a `Number`",[Mt]:"No nonce account could be found at address `$nonceAccountAddress`",[qo]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[Qo]:"WebSocket was closed before payload could be added to the send buffer",[ei]:"WebSocket connection closed",[ti]:"WebSocket failed to connect",[Jo]:"Failed to obtain a subscription id from the server",[jo]:"Could not find an API plan for RPC method: `$method`",[Yo]:"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`.",[Zo]:"HTTP error ($statusCode): $message",[Xo]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Ur]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[br]:"The provided value does not implement the `KeyPairSigner` interface",[vr]:"The provided value does not implement the `MessageModifyingSigner` interface",[Pr]:"The provided value does not implement the `MessagePartialSigner` interface",[Fr]:"The provided value does not implement any of the `MessageSigner` interfaces",[zr]:"The provided value does not implement the `TransactionModifyingSigner` interface",[wr]:"The provided value does not implement the `TransactionPartialSigner` interface",[kr]:"The provided value does not implement the `TransactionSendingSigner` interface",[Br]:"The provided value does not implement any of the `TransactionSigner` interfaces",[xr]:"More than one `TransactionSendingSigner` was identified.",[Wr]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[Vr]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[Nn]:"Cannot export a non-extractable key.",[ln]:"No digest implementation could be found.",[An]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[En]:`This runtime does not support the generation of Ed25519 key pairs.
|
|
1
|
+
'use strict';var core=require('@revibase/core'),jose=require('jose'),Xi=require('zod'),server=require('@simplewebauthn/server');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Xi__default=/*#__PURE__*/_interopDefault(Xi);var Ot=1,ft=2,mt=3,pt=4,ht=5,Mt=6,Lt=7,yt=8,Ut=9,bt=10,Ft=-32700,vt=-32603,Pt=-32602,Bt=-32601,zt=-32600,wt=-32019,kt=-32018,xt=-32017,Wt=-32016,Vt=-32015,Gt=-32014,Ht=-32013,Kt=-32012,$t=-32011,Yt=-32010,Xt=-32009,Zt=-32008,jt=-32007,qt=-32006,Jt=-32005,Qt=-32004,en=-32003,tn=-32002,nn=-32001,k=28e5,x=2800001,rn=2800002,ce=2800003,ue=2800004,de=2800005,Ie=2800006,_e=2800007,Ae=2800008,le=2800009,Ee=2800010,Re=2800011,on=323e4,an=32300001,sn=3230002,cn=3230003,un=3230004,dn=361e4,In=3610001,_n=3610002,An=3610003,ln=3610004,En=3610005,Rn=3610006,Tn=3610007,gn=3611e3,Dn=3704e3,Nn=3704001,Sn=3704002,Cn=3704003,On=3704004,fn=4128e3,mn=4128001,pn=4128002,hn=4615e3,Mn=4615001,Ln=4615002,yn=4615003,Un=4615004,bn=4615005,Fn=4615006,vn=4615007,Pn=4615008,Bn=4615009,zn=4615010,wn=4615011,kn=4615012,xn=4615013,Wn=4615014,Vn=4615015,Gn=4615016,Hn=4615017,Kn=4615018,$n=4615019,Yn=4615020,Xn=4615021,Zn=4615022,jn=4615023,qn=4615024,Jn=4615025,Qn=4615026,er=4615027,tr=4615028,nr=4615029,rr=4615030,or=4615031,ir=4615032,ar=4615033,sr=4615034,cr=4615035,ur=4615036,dr=4615037,Ir=4615038,_r=4615039,Ar=4615040,lr=4615041,Er=4615042,Rr=4615043,Tr=4615044,gr=4615045,Dr=4615046,Nr=4615047,Sr=4615048,Cr=4615049,Or=4615050,fr=4615051,mr=4615052,pr=4615053,hr=4615054,Mr=5508e3,Lr=5508001,yr=5508002,Ur=5508003,br=5508004,Fr=5508005,vr=5508006,Pr=5508007,Br=5508008,zr=5508009,wr=5508010,kr=5508011,Te=5663e3,ge=5663001,W=5663002,V=5663003,De=5663004,Ne=5663005,Se=5663006,Ce=5663007,Oe=5663008,fe=5663009,xr=5663010,Wr=5663011,me=5663012,Vr=5663013,Gr=5663014,pe=5663015,he=5663016,G=5663017,Hr=5663018,Kr=5663019,Me=5663020,H=5663021,Le=5663022,$r=705e4,Yr=7050001,Xr=7050002,Zr=7050003,jr=7050004,qr=7050005,Jr=7050006,Qr=7050007,eo=7050008,to=7050009,no=7050010,ro=7050011,oo=7050012,io=7050013,ao=7050014,so=7050015,co=7050016,uo=7050017,Io=7050018,_o=7050019,Ao=7050020,lo=7050021,Eo=7050022,Ro=7050023,To=7050024,go=7050025,Do=7050026,No=7050027,So=7050028,Co=7050029,Oo=7050030,fo=7050031,mo=7050032,po=7050033,ho=7050034,Mo=7050035,Lo=7050036,yo=7618e3,Uo=7618001,bo=7618002,Fo=7618003,K=8078e3,$=8078001,ye=8078002,Ue=8078003,be=8078004,Fe=8078005,ve=8078006,vo=8078007,Po=8078008,Bo=8078009,zo=8078010,Y=8078011,U=8078012,X=8078013,Z=8078014,wo=8078015,ko=8078016,xo=8078017,Wo=8078018,Vo=8078019,Pe=8078020,Be=8078021,Go=8078022,ze=8078023,Ho=81e5,Ko=8100001,$o=8100002,Yo=8100003,Xo=819e4,Zo=8190001,jo=8190002,qo=8190003,Jo=8190004,Qo=99e5,ei=9900001,ti=9900002,ni=9900003,ri=9900004,oi=9900005,ii=9900006;function we(e){return Array.isArray(e)?"%5B"+e.map(we).join("%2C%20")+"%5D":typeof e=="bigint"?`${e}n`:encodeURIComponent(String(e!=null&&Object.getPrototypeOf(e)===null?{...e}:e))}function ai([e,t]){return `${e}=${we(t)}`}function si(e){let t=Object.entries(e).map(ai).join("&");return Buffer.from(t,"utf8").toString("base64")}var ci={[on]:"Account not found at address: $address",[un]:"Not all accounts were decoded. Encoded accounts found at addresses: $addresses.",[cn]:"Expected decoded account at address: $address",[sn]:"Failed to decode account data at address: $address",[an]:"Accounts not found at addresses: $addresses",[le]:"Unable to find a viable program address bump seed.",[rn]:"$putativeAddress is not a base58-encoded address.",[k]:"Expected base58 encoded address to decode to a byte array of length 32. Actual length: $actualLength.",[ce]:"The `CryptoKey` must be an `Ed25519` public key.",[Re]:"$putativeOffCurveAddress is not a base58-encoded off-curve address.",[Ae]:"Invalid seeds; point must fall off the Ed25519 curve.",[ue]:"Expected given program derived address to have the following format: [Address, ProgramDerivedAddressBump].",[Ie]:"A maximum of $maxSeeds seeds, including the bump seed, may be supplied when creating an address. Received: $actual.",[_e]:"The seed at index $index with length $actual exceeds the maximum length of $maxSeedLength bytes.",[de]:"Expected program derived address bump to be in the range [0, 255], got: $bump.",[Ee]:"Program address cannot end with PDA marker.",[x]:"Expected base58-encoded address string of length in the range [32, 44]. Actual length: $actualLength.",[pt]:"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.",[K]:"Codec [$codecDescription] cannot decode empty byte arrays.",[Go]:"Enum codec cannot use lexical values [$stringValues] as discriminators. Either remove all lexical values or set `useValuesAsDiscriminators` to `false`.",[Pe]:"Sentinel [$hexSentinel] must not be present in encoded bytes [$hexEncodedBytes].",[Fe]:"Encoder and decoder must have the same fixed size, got [$encoderFixedSize] and [$decoderFixedSize].",[ve]:"Encoder and decoder must have the same max size, got [$encoderMaxSize] and [$decoderMaxSize].",[be]:"Encoder and decoder must either both be fixed-size or variable-size.",[Po]:"Enum discriminator out of range. Expected a number in [$formattedValidDiscriminators], got $discriminator.",[ye]:"Expected a fixed-size codec, got a variable-size one.",[X]:"Codec [$codecDescription] expected a positive byte length, got $bytesLength.",[Ue]:"Expected a variable-size codec, got a fixed-size one.",[Vo]:"Codec [$codecDescription] expected zero-value [$hexZeroValue] to have the same size as the provided fixed-size item [$expectedSize bytes].",[$]:"Codec [$codecDescription] expected $expected bytes, got $bytesLength.",[Wo]:"Expected byte array constant [$hexConstant] to be present in data [$hexData] at offset [$offset].",[Bo]:"Invalid discriminated union variant. Expected one of [$variants], got $value.",[zo]:"Invalid enum variant. Expected one of [$stringValues] or a number in [$formattedNumericalValues], got $variant.",[wo]:"Invalid literal union variant. Expected one of [$variants], got $value.",[vo]:"Expected [$codecDescription] to have $expected items, got $actual.",[U]:"Invalid value $value for base $base with alphabet $alphabet.",[ko]:"Literal union discriminator out of range. Expected a number between $minRange and $maxRange, got $discriminator.",[Y]:"Codec [$codecDescription] expected number to be in the range [$min, $max], got $value.",[Z]:"Codec [$codecDescription] expected offset to be in the range [0, $bytesLength], got $offset.",[Be]:"Expected sentinel [$hexSentinel] to be present in decoded bytes [$hexDecodedBytes].",[xo]:"Union variant out of range. Expected an index between $minRange and $maxRange, got $variant.",[ze]:"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?",[gn]:"No random values implementation could be found.",[Bn]:"instruction requires an uninitialized account",[jn]:"instruction tries to borrow reference for an account which is already borrowed",[qn]:"instruction left account with an outstanding borrowed reference",[Xn]:"program other than the account's owner changed the size of the account data",[bn]:"account data too small for instruction",[Zn]:"instruction expected an executable account",[Dr]:"An account does not have enough lamports to be rent-exempt",[Sr]:"Program arithmetic overflowed",[gr]:"Failed to serialize or deserialize account data: $encodedData",[hr]:"Builtin programs must consume compute units",[ir]:"Cross-program invocation call depth too deep",[Ir]:"Computational budget exceeded",[Qn]:"custom program error: #$code",[Hn]:"instruction contains duplicate accounts",[Jn]:"instruction modifications of multiply-passed account differ",[rr]:"executable accounts must be rent exempt",[tr]:"instruction changed executable accounts data",[nr]:"instruction changed the balance of an executable account",[Kn]:"instruction changed executable bit of an account",[Wn]:"instruction modified data of an account it does not own",[xn]:"instruction spent from the balance of an account it does not own",[Mn]:"generic instruction error",[Or]:"Provided owner is not allowed",[Rr]:"Account is immutable",[Tr]:"Incorrect authority provided",[vn]:"incorrect program id for instruction",[Fn]:"insufficient funds for instruction",[Un]:"invalid account data for instruction",[Nr]:"Invalid account owner",[Ln]:"invalid program argument",[er]:"program returned invalid error code",[yn]:"invalid instruction data",[dr]:"Failed to reallocate account data",[ur]:"Provided seeds do not result in a valid address",[fr]:"Accounts data allocations exceeded the maximum allowed per transaction",[mr]:"Max accounts exceeded",[pr]:"Max instruction trace length exceeded",[cr]:"Length of the seed is too long for address generation",[ar]:"An account required by the instruction is missing",[Pn]:"missing required signature for instruction",[kn]:"instruction illegally modified the program id of an account",[Yn]:"insufficient account keys for instruction",[_r]:"Cross-program invocation with unauthorized signer or writable account",[Ar]:"Failed to create program execution environment",[Er]:"Program failed to compile",[lr]:"Program failed to complete",[Gn]:"instruction modified data of a read-only account",[Vn]:"instruction changed the balance of a read-only account",[sr]:"Cross-program invocation reentrancy not allowed for this instruction",[$n]:"instruction modified rent epoch of an account",[wn]:"sum of account balances before and after instruction do not match",[zn]:"instruction requires an initialized account",[hn]:"",[or]:"Unsupported program id",[Cr]:"Unsupported sysvar",[oi]:"Invalid instruction plan kind: $kind.",[bo]:"The provided instruction plan is empty.",[Fo]:"The provided transaction plan failed to execute. See the `transactionPlanResult` attribute and the `cause` error for more details.",[yo]:"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).",[ii]:"Invalid transaction plan kind: $kind.",[Uo]:"No more instructions to pack; the message packer has completed the instruction plan.",[fn]:"The instruction does not have any accounts.",[mn]:"The instruction does not have any data.",[pn]:"Expected instruction to have progress address $expectedProgramAddress, got $actualProgramAddress.",[ht]:"Expected base58 encoded blockhash to decode to a byte array of length 32. Actual length: $actualLength.",[ft]:"The nonce `$expectedNonceValue` is no longer valid. It has advanced to `$actualNonceValue`",[ti]:"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",[ri]:"Invariant violation: This data publisher does not publish to the channel named `$channelName`. Supported channels include $supportedChannelNames.",[ei]:"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",[Qo]:"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",[ni]:"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",[vt]:"JSON-RPC error: Internal JSON-RPC error ($__serverMessage)",[Pt]:"JSON-RPC error: Invalid method parameter(s) ($__serverMessage)",[zt]:"JSON-RPC error: The JSON sent is not a valid `Request` object ($__serverMessage)",[Bt]:"JSON-RPC error: The method does not exist / is not available ($__serverMessage)",[Ft]:"JSON-RPC error: An error occurred on the server while parsing the JSON text ($__serverMessage)",[Kt]:"$__serverMessage",[nn]:"$__serverMessage",[Qt]:"$__serverMessage",[Gt]:"$__serverMessage",[xt]:"Epoch rewards period still active at slot $slot",[Yt]:"$__serverMessage",[Xt]:"$__serverMessage",[wt]:"Failed to query long-term storage; please try again",[Wt]:"Minimum context slot has not been reached",[Jt]:"Node is unhealthy; behind by $numSlotsBehind slots",[Zt]:"No snapshot",[tn]:"Transaction simulation failed",[kt]:"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",[jt]:"$__serverMessage",[$t]:"Transaction history is not available from this node",[qt]:"$__serverMessage",[Ht]:"Transaction signature length mismatch",[en]:"Transaction signature verification failure",[Vt]:"$__serverMessage",[Dn]:"Key pair bytes must be of length 64, got $byteLength.",[Nn]:"Expected private key bytes with length 32. Actual length: $actualLength.",[Sn]:"Expected base58-encoded signature to decode to a byte array of length 64. Actual length: $actualLength.",[On]:"The provided private key does not match the provided public key.",[Cn]:"Expected base58-encoded signature string of length in the range [64, 88]. Actual length: $actualLength.",[Mt]:"Lamports value must be in the range [0, 2e64-1]",[Lt]:"`$value` cannot be parsed as a `BigInt`",[bt]:"$message",[yt]:"`$value` cannot be parsed as a `Number`",[mt]:"No nonce account could be found at address `$nonceAccountAddress`",[Xo]:"The notification name must end in 'Notifications' and the API must supply a subscription plan creator function for the notification '$notificationName'.",[jo]:"WebSocket was closed before payload could be added to the send buffer",[qo]:"WebSocket connection closed",[Jo]:"WebSocket failed to connect",[Zo]:"Failed to obtain a subscription id from the server",[Yo]:"Could not find an API plan for RPC method: `$method`",[Ho]:"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`.",[$o]:"HTTP error ($statusCode): $message",[Ko]:"HTTP header(s) forbidden: $headers. Learn more at https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name.",[Mr]:"Multiple distinct signers were identified for address `$address`. Please ensure that you are using the same signer instance for each address.",[Lr]:"The provided value does not implement the `KeyPairSigner` interface",[Ur]:"The provided value does not implement the `MessageModifyingSigner` interface",[br]:"The provided value does not implement the `MessagePartialSigner` interface",[yr]:"The provided value does not implement any of the `MessageSigner` interfaces",[vr]:"The provided value does not implement the `TransactionModifyingSigner` interface",[Pr]:"The provided value does not implement the `TransactionPartialSigner` interface",[Br]:"The provided value does not implement the `TransactionSendingSigner` interface",[Fr]:"The provided value does not implement any of the `TransactionSigner` interfaces",[zr]:"More than one `TransactionSendingSigner` was identified.",[wr]:"No `TransactionSendingSigner` was identified. Please provide a valid `TransactionWithSingleSendingSigner` transaction.",[kr]:"Wallet account signers do not support signing multiple messages/transactions in a single operation",[Tn]:"Cannot export a non-extractable key.",[In]:"No digest implementation could be found.",[dn]:"Cryptographic operations are only allowed in secure browser contexts. Read more here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts.",[_n]:`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.`,[Rn]:"No signature verification implementation could be found.",[Tn]:"No key generation implementation could be found.",[gn]:"No signing implementation could be found.",[Dn]:"No key export implementation could be found.",[vt]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[_o]:"Transaction processing left an account with an outstanding borrowed reference",[jr]:"Account in use",[qr]:"Account loaded twice",[Jr]:"Attempt to debit an account but found no record of a prior credit.",[Do]:"Transaction loads an address table account that doesn't exist",[no]:"This transaction has already been processed",[ro]:"Blockhash not found",[oo]:"Loader call chain is too deep",[Io]:"Transactions are currently disabled due to cluster maintenance",[po]:"Transaction contains a duplicate instruction ($index) that is not allowed",[eo]:"Insufficient funds for fee",[ho]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[to]:"This account may not be used to pay transaction fees",[ao]:"Transaction contains an invalid account reference",[So]:"Transaction loads an address table account with invalid data",[Co]:"Transaction address table lookup uses an invalid index",[No]:"Transaction loads an address table account with an invalid owner",[Lo]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[co]:"This program may not be used for executing instructions",[Oo]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[Eo]:"Transaction loads a writable account that cannot be written",[Mo]:"Transaction exceeded max loaded accounts data size cap",[io]:"Transaction requires a fee but has no signature present",[Qr]:"Attempt to load a program that does not exist",[Uo]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[yo]:"ResanitizationNeeded",[uo]:"Transaction failed to sanitize accounts offsets correctly",[so]:"Transaction did not pass signature verification",[go]:"Transaction locked too many accounts",[bo]:"Sum of account balances before and after transaction do not match",[Zr]:"The transaction failed with the error `$errorName`",[lo]:"Transaction version is unsupported",[To]:"Transaction would exceed account data limit within the block",[mo]:"Transaction would exceed total account data limit",[Ro]:"Transaction would exceed max account limit within the block",[Ao]:"Transaction would exceed max Block Cost Limit",[fo]:"Transaction would exceed max Vote Cost Limit",[Le]:"Attempted to sign a transaction with an address that is not a signer for it",[Gr]:"Transaction is missing an address at index: $index.",[ye]:"Transaction has no expected signers therefore it cannot be encoded",[Ue]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[K]:"Transaction does not have a blockhash lifetime",[$]:"Transaction is not a durable nonce transaction",[Oe]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[fe]:"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",[pe]:"No fee payer set in CompiledTransaction",[me]:"Could not find program address at index $index",[Yr]:"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",[Xr]:"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",[Hr]:"Transaction is missing a fee payer.",[Me]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[$r]:"Transaction first instruction is not advance nonce account instruction.",[Kr]:"Transaction with no instructions cannot be durable nonce transaction.",[Ne]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[Se]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Y]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[he]:"Transaction is missing signatures for addresses: $addresses.",[Ce]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[X]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[be]:"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."},D="i",T="t";function _i(e,t={}){let n=Ii[e];if(n.length===0)return "";let r;function o(i){if(r[T]===2){let s=n.slice(r[D]+1,i);a.push(s in t?`${t[s]}`:`$${s}`);}else r[T]===1&&a.push(n.slice(r[D],i));}let a=[];return n.split("").forEach((i,s)=>{if(s===0){r={[D]:0,[T]:n[0]==="\\"?0:n[0]==="$"?2:1};return}let c;switch(r[T]){case 0:c={[D]:s,[T]:1};break;case 1:i==="\\"?c={[D]:s,[T]:0}:i==="$"&&(c={[D]:s,[T]:2});break;case 2:i==="\\"?c={[D]:s,[T]:0}:i==="$"?c={[D]:s,[T]:2}:i.match(/\w/)||(c={[D]:s,[T]:1});break}c&&(r!==c&&o(s),r=c);}),o(),a.join("")}function Ai(e,t={}){if(process.env.NODE_ENV!=="production")return _i(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${di(t)}'`),`${n}\``}}var l=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;t&&Object.entries(Object.getOwnPropertyDescriptors(t)).forEach(([a,i])=>{a==="cause"?r={cause:i.value}:(n===void 0&&(n={}),Object.defineProperty(n,a,i));});let o=Ai(e,n);super(o,r),this.context=n===void 0?{}:n,this.context.__code=e,this.name="SolanaError";}};function li(e,t){if(e.length>=t)return e;let n=new Uint8Array(t).fill(0);return n.set(e),n}var Ei=(e,t)=>li(e.length<=t?e:e.slice(0,t),t);function Ge(e,t){return "fixedSize"in t?t.fixedSize:t.getSizeFromValue(e)}function N(e){return Object.freeze({...e,encode:t=>{let n=new Uint8Array(Ge(t,e));return e.write(t,n,0),n}})}function A(e){return Object.freeze({...e,decode:(t,n=0)=>e.read(t,n)[0]})}function p(e){return "fixedSize"in e&&typeof e.fixedSize=="number"}function Ri(e){return !p(e)}function He(e,t,n=0){if(t.length-n<=0)throw new l(Z,{codecDescription:e})}function B(e,t,n,r=0){let o=n.length-r;if(o<t)throw new l(j,{bytesLength:o,codecDescription:e,expected:t})}function Ve(e,t,n){if(t<0||t>n)throw new l(Q,{bytesLength:n,codecDescription:e,offset:t})}function U(e,t){return N({fixedSize:t,write:(n,r,o)=>{let a=e.encode(n),i=a.length>t?a.slice(0,t):a;return r.set(i,o),o+t}})}function h(e,t){return A({fixedSize:t,read:(n,r)=>{B("fixCodecSize",t,n,r),(r>0||n.length>t)&&(n=n.slice(r,r+t)),p(e)&&(n=Ei(n,e.fixedSize));let[o]=e.read(n,0);return [o,r+t]}})}function Ti(e,t){return A({...e,read:(n,r)=>{let o=d=>gi(d,n.length),a=t.preOffset?t.preOffset({bytes:n,preOffset:r,wrapBytes:o}):r;Ve("offsetDecoder",a,n.length);let[i,s]=e.read(n,a),c=t.postOffset?t.postOffset({bytes:n,newPreOffset:a,postOffset:s,preOffset:r,wrapBytes:o}):s;return Ve("offsetDecoder",c,n.length),[i,c]}})}function gi(e,t){return t===0?0:(e%t+t)%t}function Di(e,t){if(p(e)){let n=t(e.fixedSize);if(n<0)throw new l(J,{bytesLength:n,codecDescription:"resizeDecoder"});return A({...e,fixedSize:n})}return e}function Ke(e,t){return Ti(Di(e,n=>n+t),{postOffset:({postOffset:n})=>n+t})}function b(e,t){return N({...Ri(e)?{...e,getSizeFromValue:n=>e.getSizeFromValue(t(n))}:e,write:(n,r,o)=>e.write(t(n),r,o)})}function z(e,t){return A({...e,read:(n,r)=>{let[o,a]=e.read(n,r);return [t(o,n,r),a]}})}function Xe(e,t,n=t){if(!t.match(new RegExp(`^[${e}]*$`)))throw new l(P,{alphabet:e,base:e.length,value:n})}var Ni=e=>N({getSizeFromValue:t=>{let[n,r]=$e(t,e[0]);if(!r)return t.length;let o=Ye(r,e);return n.length+Math.ceil(o.toString(16).length/2)},write(t,n,r){if(Xe(e,t),t==="")return r;let[o,a]=$e(t,e[0]);if(!a)return n.set(new Uint8Array(o.length).fill(0),r),r+o.length;let i=Ye(a,e),s=[];for(;i>0n;)s.unshift(Number(i%256n)),i/=256n;let c=[...Array(o.length).fill(0),...s];return n.set(c,r),r+c.length}}),Si=e=>A({read(t,n){let r=n===0?t:t.slice(n);if(r.length===0)return ["",0];let o=r.findIndex(c=>c!==0);o=o===-1?r.length:o;let a=e[0].repeat(o);if(o===r.length)return [a,t.length];let i=r.slice(o).reduce((c,d)=>c*256n+BigInt(d),0n),s=Ci(i,e);return [a+s,t.length]}});function $e(e,t){let[n,r]=e.split(new RegExp(`((?!${t}).*)`));return [n,r]}function Ye(e,t){let n=BigInt(t.length),r=0n;for(let o of e)r*=n,r+=BigInt(t.indexOf(o));return r}function Ci(e,t){let n=BigInt(t.length),r=[];for(;e>0n;)r.unshift(t[Number(e%n)]),e/=n;return r.join("")}var Ze="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",je=()=>Ni(Ze),w=()=>Si(Ze);var Oi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k=()=>N({getSizeFromValue:e=>Buffer.from(e,"base64").length,write(e,t,n){Xe(Oi,e.replace(/=/g,""));let r=Buffer.from(e,"base64");return t.set(r,n),r.length+n}}),S=()=>A({read:(e,t=0)=>[Buffer.from(e,t).toString("base64"),e.length]});var ee,te;function qe(){return ee||(ee=je()),ee}function fi(){return te||(te=w()),te}function mi(e){if(e.length<32||e.length>44)throw new l(H,{actualLength:e.length});let r=qe().encode(e).byteLength;if(r!==32)throw new l(G,{actualLength:r})}function M(e){return mi(e),e}function ne(){return b(U(qe(),32),e=>M(e))}function Je(){return h(fi(),32)}function pi(e,t,n,r){if(r<t||r>n)throw new l(q,{codecDescription:e,max:n,min:t,value:r})}function Qe(e){return e?.endian!==1}function hi(e){return N({fixedSize:e.size,write(t,n,r){e.range&&pi(e.name,e.range[0],e.range[1],t);let o=new ArrayBuffer(e.size);return e.set(new DataView(o),t,Qe(e.config)),n.set(new Uint8Array(o),r),r+e.size}})}function et(e){return A({fixedSize:e.size,read(t,n=0){He(e.name,t,n),B(e.name,e.size,t,n);let r=new DataView(Mi(t,n,e.size));return [e.get(r,Qe(e.config)),n+e.size]}})}function Mi(e,t,n){let r=e.byteOffset+(t??0),o=n??e.byteLength;return e.buffer.slice(r,r+o)}var re=()=>A({maxSize:3,read:(e,t)=>{let n=0,r=0;for(;++r;){let o=r-1,a=e[t+o],i=127&a;if(n|=i<<o*7,(a&128)===0)break}return [n,t+r]}});var tt=(e={})=>et({config:e,get:(t,n)=>t.getUint32(0,n),name:"u32",size:4});var nt=(e={})=>hi({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(t,n,r)=>t.setBigUint64(0,BigInt(n),r),size:8});var oe=()=>et({get:e=>e.getUint8(0),name:"u8",size:1});function x(e){return e.reduce((t,n)=>t===null||n===null?null:t+n,0)}function ie(e){return p(e)?e.fixedSize:null}function ae(e){return p(e)?e.fixedSize:e.maxSize??null}function se(e,t={}){let n=t.size??tt(),r=ie(e),o=rt(n,r),a=rt(n,ae(e))??void 0;return A({...o!==null?{fixedSize:o}:{maxSize:a},read:(i,s)=>{let c=[];if(typeof n=="object"&&i.slice(s).length===0)return [c,s];if(n==="remainder"){for(;s<i.length;){let[u,I]=e.read(i,s);s=I,c.push(u);}return [c,s]}let[d,_]=typeof n=="number"?[n,s]:n.read(i,s);s=_;for(let u=0;u<d;u+=1){let[I,E]=e.read(i,s);s=E,c.push(I);}return [c,s]}})}function rt(e,t){return typeof e!="number"?null:e===0?0:t===null?null:t*e}function ce(){return A({read:(e,t)=>{let n=e.slice(t);return [n,t+n.length]}})}function ot(e){let t=x(e.map(ie)),n=x(e.map(ae))??void 0;return A({...t===null?{maxSize:n}:{fixedSize:t},read:(r,o)=>{let a=[];return e.forEach(i=>{let[s,c]=i.read(r,o);a.push(s),o=c;}),[a,o]}})}function it(e){let t=e.map(([,o])=>o),n=x(t.map(ie)),r=x(t.map(ae))??void 0;return A({...n===null?{maxSize:r}:{fixedSize:n},read:(o,a)=>{let i={};return e.forEach(([s,c])=>{let[d,_]=c.read(o,a);a=_,i[s]=d;}),[i,a]}})}var Li=0,at=128;function st(){return A({maxSize:1,read:(e,t)=>{let n=e[t];if((n&at)===0)return ["legacy",t];{let r=n^at;if(r>Li)throw new l(X,{unsupportedVersion:r});return [r,t+1]}}})}function ct(){return z(it([["signatures",se(h(ce(),64),{size:re()})],["messageBytes",ce()]]),yi)}function yi(e){let{messageBytes:t,signatures:n}=e,r=ot([st(),Ke(oe(),2),se(Je(),{size:re()})]),[o,a,i]=r.decode(t),s=i.slice(0,a);if(s.length!==n.length)throw new l(Y,{numRequiredSignatures:a,signaturesLength:n.length,signerAddresses:s});let c={};return s.forEach((d,_)=>{let u=n[_];u.every(I=>I===0)?c[d]=null:c[d]=u;}),{messageBytes:t,signatures:Object.freeze(c)}}function ut(e){if(typeof window>"u")throw new Error("Function can only be called in a browser environment");let t=window.innerWidth||window.screen.availWidth,n=window.innerHeight||window.screen.availHeight,r=t<=768,o,a,i,s;if(r)o=t,a=n,i=0,s=0;else {let d=window.screenLeft??window.screenX??0,_=window.screenTop??window.screenY??0,u=window.innerWidth??document.documentElement.clientWidth??window.screen.width,I=window.innerHeight??document.documentElement.clientHeight??window.screen.height;o=500,a=600,s=Math.round(d+(u-o)/2),i=Math.round(_+(I-a)/2);}let c=["popup=yes",`width=${o}`,`height=${a}`,`top=${i}`,`left=${s}`,"toolbar=no","location=no","status=no","menubar=no","scrollbars=yes","resizable=yes"].join(",");return window.open(e??"","_blank",c)}function dt(e){let t=e.domain?`${e.domain} wants you to sign in with your account.`:"Sign in with your account.",n=[];return e.nonce&&n.push(`Nonce: ${e.nonce}`),n.length>0?`${t}
|
|
5
|
+
For a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.`,[An]:"No signature verification implementation could be found.",[ln]:"No key generation implementation could be found.",[En]:"No signing implementation could be found.",[Rn]:"No key export implementation could be found.",[Ut]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[co]:"Transaction processing left an account with an outstanding borrowed reference",[Yr]:"Account in use",[Xr]:"Account loaded twice",[Zr]:"Attempt to debit an account but found no record of a prior credit.",[Ro]:"Transaction loads an address table account that doesn't exist",[Qr]:"This transaction has already been processed",[eo]:"Blockhash not found",[to]:"Loader call chain is too deep",[so]:"Transactions are currently disabled due to cluster maintenance",[Oo]:"Transaction contains a duplicate instruction ($index) that is not allowed",[qr]:"Insufficient funds for fee",[fo]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[Jr]:"This account may not be used to pay transaction fees",[ro]:"Transaction contains an invalid account reference",[go]:"Transaction loads an address table account with invalid data",[Do]:"Transaction address table lookup uses an invalid index",[To]:"Transaction loads an address table account with an invalid owner",[po]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[io]:"This program may not be used for executing instructions",[No]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[_o]:"Transaction loads a writable account that cannot be written",[mo]:"Transaction exceeded max loaded accounts data size cap",[no]:"Transaction requires a fee but has no signature present",[jr]:"Attempt to load a program that does not exist",[Mo]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[ho]:"ResanitizationNeeded",[ao]:"Transaction failed to sanitize accounts offsets correctly",[oo]:"Transaction did not pass signature verification",[Eo]:"Transaction locked too many accounts",[Lo]:"Sum of account balances before and after transaction do not match",[$r]:"The transaction failed with the error `$errorName`",[Io]:"Transaction version is unsupported",[lo]:"Transaction would exceed account data limit within the block",[Co]:"Transaction would exceed total account data limit",[Ao]:"Transaction would exceed max account limit within the block",[uo]:"Transaction would exceed max Block Cost Limit",[So]:"Transaction would exceed max Vote Cost Limit",[pe]:"Attempted to sign a transaction with an address that is not a signer for it",[xr]:"Transaction is missing an address at index: $index.",[he]:"Transaction has no expected signers therefore it cannot be encoded",[Me]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[W]:"Transaction does not have a blockhash lifetime",[V]:"Transaction is not a durable nonce transaction",[Ne]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Se]:"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",[Oe]:"No fee payer set in CompiledTransaction",[Ce]:"Could not find program address at index $index",[Hr]:"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",[Kr]:"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",[Wr]:"Transaction is missing a fee payer.",[me]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[Gr]:"Transaction first instruction is not advance nonce account instruction.",[Vr]:"Transaction with no instructions cannot be durable nonce transaction.",[Te]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[ge]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[G]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[fe]:"Transaction is missing signatures for addresses: $addresses.",[De]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[H]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[Le]:"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."},g="i",E="t";function ui(e,t={}){let n=ci[e];if(n.length===0)return "";let r;function o(a){if(r[E]===2){let s=n.slice(r[g]+1,a);i.push(s in t?`${t[s]}`:`$${s}`);}else r[E]===1&&i.push(n.slice(r[g],a));}let i=[];return n.split("").forEach((a,s)=>{if(s===0){r={[g]:0,[E]:n[0]==="\\"?0:n[0]==="$"?2:1};return}let c;switch(r[E]){case 0:c={[g]:s,[E]:1};break;case 1:a==="\\"?c={[g]:s,[E]:0}:a==="$"&&(c={[g]:s,[E]:2});break;case 2:a==="\\"?c={[g]:s,[E]:0}:a==="$"?c={[g]:s,[E]:2}:a.match(/\w/)||(c={[g]:s,[E]:1});break}c&&(r!==c&&o(s),r=c);}),o(),i.join("")}function di(e,t={}){if(process.env.NODE_ENV!=="production")return ui(e,t);{let n=`Solana error #${e}; Decode this error by running \`npx @solana/errors decode -- ${e}`;return Object.keys(t).length&&(n+=` '${si(t)}'`),`${n}\``}}var l=class extends Error{cause=this.cause;context;constructor(...[e,t]){let n,r;t&&Object.entries(Object.getOwnPropertyDescriptors(t)).forEach(([i,a])=>{i==="cause"?r={cause:a.value}:(n===void 0&&(n={}),Object.defineProperty(n,i,a));});let o=di(e,n);super(o,r),this.context=n===void 0?{}:n,this.context.__code=e,this.name="SolanaError";}};function Ii(e,t){if(e.length>=t)return e;let n=new Uint8Array(t).fill(0);return n.set(e),n}var _i=(e,t)=>Ii(e.length<=t?e:e.slice(0,t),t);function xe(e,t){return "fixedSize"in t?t.fixedSize:t.getSizeFromValue(e)}function D(e){return Object.freeze({...e,encode:t=>{let n=new Uint8Array(xe(t,e));return e.write(t,n,0),n}})}function A(e){return Object.freeze({...e,decode:(t,n=0)=>e.read(t,n)[0]})}function O(e){return "fixedSize"in e&&typeof e.fixedSize=="number"}function Ai(e){return !O(e)}function We(e,t,n=0){if(t.length-n<=0)throw new l(K,{codecDescription:e})}function b(e,t,n,r=0){let o=n.length-r;if(o<t)throw new l($,{bytesLength:o,codecDescription:e,expected:t})}function ke(e,t,n){if(t<0||t>n)throw new l(Z,{bytesLength:n,codecDescription:e,offset:t})}function M(e,t){return D({fixedSize:t,write:(n,r,o)=>{let i=e.encode(n),a=i.length>t?i.slice(0,t):i;return r.set(a,o),o+t}})}function f(e,t){return A({fixedSize:t,read:(n,r)=>{b("fixCodecSize",t,n,r),(r>0||n.length>t)&&(n=n.slice(r,r+t)),O(e)&&(n=_i(n,e.fixedSize));let[o]=e.read(n,0);return [o,r+t]}})}function li(e,t){return A({...e,read:(n,r)=>{let o=d=>Ei(d,n.length),i=t.preOffset?t.preOffset({bytes:n,preOffset:r,wrapBytes:o}):r;ke("offsetDecoder",i,n.length);let[a,s]=e.read(n,i),c=t.postOffset?t.postOffset({bytes:n,newPreOffset:i,postOffset:s,preOffset:r,wrapBytes:o}):s;return ke("offsetDecoder",c,n.length),[a,c]}})}function Ei(e,t){return t===0?0:(e%t+t)%t}function Ri(e,t){if(O(e)){let n=t(e.fixedSize);if(n<0)throw new l(X,{bytesLength:n,codecDescription:"resizeDecoder"});return A({...e,fixedSize:n})}return e}function Ve(e,t){return li(Ri(e,n=>n+t),{postOffset:({postOffset:n})=>n+t})}function L(e,t){return D({...Ai(e)?{...e,getSizeFromValue:n=>e.getSizeFromValue(t(n))}:e,write:(n,r,o)=>e.write(t(n),r,o)})}function F(e,t){return A({...e,read:(n,r)=>{let[o,i]=e.read(n,r);return [t(o,n,r),i]}})}function Ke(e,t,n=t){if(!t.match(new RegExp(`^[${e}]*$`)))throw new l(U,{alphabet:e,base:e.length,value:n})}var Ti=e=>D({getSizeFromValue:t=>{let[n,r]=Ge(t,e[0]);if(!r)return t.length;let o=He(r,e);return n.length+Math.ceil(o.toString(16).length/2)},write(t,n,r){if(Ke(e,t),t==="")return r;let[o,i]=Ge(t,e[0]);if(!i)return n.set(new Uint8Array(o.length).fill(0),r),r+o.length;let a=He(i,e),s=[];for(;a>0n;)s.unshift(Number(a%256n)),a/=256n;let c=[...Array(o.length).fill(0),...s];return n.set(c,r),r+c.length}}),gi=e=>A({read(t,n){let r=n===0?t:t.slice(n);if(r.length===0)return ["",0];let o=r.findIndex(c=>c!==0);o=o===-1?r.length:o;let i=e[0].repeat(o);if(o===r.length)return [i,t.length];let a=r.slice(o).reduce((c,d)=>c*256n+BigInt(d),0n),s=Di(a,e);return [i+s,t.length]}});function Ge(e,t){let[n,r]=e.split(new RegExp(`((?!${t}).*)`));return [n,r]}function He(e,t){let n=BigInt(t.length),r=0n;for(let o of e)r*=n,r+=BigInt(t.indexOf(o));return r}function Di(e,t){let n=BigInt(t.length),r=[];for(;e>0n;)r.unshift(t[Number(e%n)]),e/=n;return r.join("")}var $e="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Ye=()=>Ti($e),v=()=>gi($e);var Ni="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xe=()=>D({getSizeFromValue:e=>Buffer.from(e,"base64").length,write(e,t,n){Ke(Ni,e.replace(/=/g,""));let r=Buffer.from(e,"base64");return t.set(r,n),r.length+n}}),N=()=>A({read:(e,t=0)=>[Buffer.from(e,t).toString("base64"),e.length]});var j,q;function Ze(){return j||(j=Ye()),j}function Si(){return q||(q=v()),q}function Ci(e){if(e.length<32||e.length>44)throw new l(x,{actualLength:e.length});let r=Ze().encode(e).byteLength;if(r!==32)throw new l(k,{actualLength:r})}function m(e){return Ci(e),e}function J(){return L(M(Ze(),32),e=>m(e))}function je(){return f(Si(),32)}function Oi(e,t,n,r){if(r<t||r>n)throw new l(Y,{codecDescription:e,max:n,min:t,value:r})}function qe(e){return e?.endian!==1}function fi(e){return D({fixedSize:e.size,write(t,n,r){e.range&&Oi(e.name,e.range[0],e.range[1],t);let o=new ArrayBuffer(e.size);return e.set(new DataView(o),t,qe(e.config)),n.set(new Uint8Array(o),r),r+e.size}})}function Je(e){return A({fixedSize:e.size,read(t,n=0){We(e.name,t,n),b(e.name,e.size,t,n);let r=new DataView(mi(t,n,e.size));return [e.get(r,qe(e.config)),n+e.size]}})}function mi(e,t,n){let r=e.byteOffset+(t??0),o=n??e.byteLength;return e.buffer.slice(r,r+o)}var Q=()=>A({maxSize:3,read:(e,t)=>{let n=0,r=0;for(;++r;){let o=r-1,i=e[t+o],a=127&i;if(n|=a<<o*7,(i&128)===0)break}return [n,t+r]}});var Qe=(e={})=>Je({config:e,get:(t,n)=>t.getUint32(0,n),name:"u32",size:4});var et=(e={})=>fi({config:e,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(t,n,r)=>t.setBigUint64(0,BigInt(n),r),size:8});var ee=()=>Je({get:e=>e.getUint8(0),name:"u8",size:1});function P(e){return e.reduce((t,n)=>t===null||n===null?null:t+n,0)}function te(e){return O(e)?e.fixedSize:null}function ne(e){return O(e)?e.fixedSize:e.maxSize??null}function re(e,t={}){let n=t.size??Qe(),r=te(e),o=tt(n,r),i=tt(n,ne(e))??void 0;return A({...o!==null?{fixedSize:o}:{maxSize:i},read:(a,s)=>{let c=[];if(typeof n=="object"&&a.slice(s).length===0)return [c,s];if(n==="remainder"){for(;s<a.length;){let[u,I]=e.read(a,s);s=I,c.push(u);}return [c,s]}let[d,_]=typeof n=="number"?[n,s]:n.read(a,s);s=_;for(let u=0;u<d;u+=1){let[I,T]=e.read(a,s);s=T,c.push(I);}return [c,s]}})}function tt(e,t){return typeof e!="number"?null:e===0?0:t===null?null:t*e}function oe(){return A({read:(e,t)=>{let n=e.slice(t);return [n,t+n.length]}})}function nt(e){let t=P(e.map(te)),n=P(e.map(ne))??void 0;return A({...t===null?{maxSize:n}:{fixedSize:t},read:(r,o)=>{let i=[];return e.forEach(a=>{let[s,c]=a.read(r,o);i.push(s),o=c;}),[i,o]}})}function rt(e){let t=e.map(([,o])=>o),n=P(t.map(te)),r=P(t.map(ne))??void 0;return A({...n===null?{maxSize:r}:{fixedSize:n},read:(o,i)=>{let a={};return e.forEach(([s,c])=>{let[d,_]=c.read(o,i);i=_,a[s]=d;}),[a,i]}})}var pi=0,ot=128;function it(){return A({maxSize:1,read:(e,t)=>{let n=e[t];if((n&ot)===0)return ["legacy",t];{let r=n^ot;if(r>pi)throw new l(H,{unsupportedVersion:r});return [r,t+1]}}})}function at(){return F(rt([["signatures",re(f(oe(),64),{size:Q()})],["messageBytes",oe()]]),hi)}function hi(e){let{messageBytes:t,signatures:n}=e,r=nt([it(),Ve(ee(),2),re(je(),{size:Q()})]),[o,i,a]=r.decode(t),s=a.slice(0,i);if(s.length!==n.length)throw new l(G,{numRequiredSignatures:i,signaturesLength:n.length,signerAddresses:s});let c={};return s.forEach((d,_)=>{let u=n[_];u.every(I=>I===0)?c[d]=null:c[d]=u;}),{messageBytes:t,signatures:Object.freeze(c)}}function st(e){if(typeof window>"u")throw new Error("Function can only be called in a browser environment");let t=window.innerWidth||window.screen.availWidth,n=window.innerHeight||window.screen.availHeight,r=t<=768,o,i,a,s;if(r)o=t,i=n,a=0,s=0;else {let d=window.screenLeft??window.screenX??0,_=window.screenTop??window.screenY??0,u=window.innerWidth??document.documentElement.clientWidth??window.screen.width,I=window.innerHeight??document.documentElement.clientHeight??window.screen.height;o=500,i=600,s=Math.round(d+(u-o)/2),a=Math.round(_+(I-i)/2);}let c=["popup=yes",`width=${o}`,`height=${i}`,`top=${a}`,`left=${s}`,"toolbar=no","location=no","status=no","menubar=no","scrollbars=yes","resizable=yes"].join(",");return window.open(e??"","_blank",c)}function ct(e){let t=e.domain?`${e.domain} wants you to sign in with your account.`:"Sign in with your account.",n=[];return e.nonce&&n.push(`Nonce: ${e.nonce}`),n.length>0?`${t}
|
|
6
6
|
|
|
7
7
|
${n.join(`
|
|
8
|
-
`)}`:t}async function Qa(e){let{rid:t,redirectOrigin:n}=e.initialize();await new Promise(a=>setTimeout(a,0));let r={phase:"start",rid:t,validTill:Date.now()+6e5,data:{type:"message",payload:dt({domain:n,nonce:S().decode(crypto.getRandomValues(new Uint8Array(16)))})},redirectOrigin:n},o=new AbortController;return e.channelId||e.sendPayloadToProvider({rid:t,signal:o.signal}).catch(a=>o.abort(a)),await e.onClientAuthorizationCallback(r,o.signal,await e.getDeviceSignature(),e.channelId)}async function os(e,t){let{redirectOrigin:n,rid:r}=e.initialize();await new Promise(E=>setTimeout(E,0));let{instructions:o,signer:a,addressesByLookupTableAddress:i,hasTxManager:s=true}=t,c=core.prepareTransactionMessage({payer:M(a.walletAddress),instructions:o,addressesByLookupTableAddress:i}),d=await core.getSettingsFromIndex(a.settingsIndexWithAddress.index),_={transactionMessageBytes:S().decode(c),transactionAddress:d,transactionActionType:s?"execute":"create_with_preauthorized_execution"},u={phase:"start",rid:r,validTill:Date.now()+6e5,data:{type:"transaction",payload:_,sendTx:true,additionalSigners:t.additionalSigners},redirectOrigin:n,signer:a.publicKey},I=new AbortController;return e.channelId||e.sendPayloadToProvider({rid:r,signal:I.signal}).catch(E=>I.abort(E)),await e.onClientAuthorizationCallback(u,I.signal,await e.getDeviceSignature(),e.channelId)}var W="11111111111111111111111111111111";var It=0,_t=1,At=2,lt=3,Et=4,Rt=5,Tt=6,gt=7,Dt=8;process.env.NODE_ENV!=="production"&&({[It]:"an account with the same address already exists",[Rt]:"provided address does not match addressed derived from seed",[lt]:"cannot allocate account data of this length",[At]:"cannot assign account to this program id",[Et]:"length of requested seed is too long",[gt]:"stored nonce is still in recent_blockhashes",[Tt]:"advancing stored nonce requires a populated RecentBlockhashes sysvar",[Dt]:"specified nonce does not match stored nonce",[_t]:"account does not have enough SOL to perform the operation"});var ue="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";async function ym(e,t){if(t.amount<=0)throw new Error("Transfer amount must be greater than 0");if(!t.destination||typeof t.destination!="string")throw new Error("Destination address is required");let{rid:n,redirectOrigin:r}=e.initialize();await new Promise(I=>setTimeout(I,0));let{mint:o,tokenProgram:a=ue,amount:i,destination:s,signer:c}=t,d={transactionActionType:"transfer_intent",transactionAddress:o?a:W,transactionMessageBytes:S().decode(new Uint8Array([...nt().encode(i),...ne().encode(M(s)),...ne().encode(M(o??W))]))},_={phase:"start",rid:n,validTill:Date.now()+6e5,data:{type:"transaction",payload:d,sendTx:true},redirectOrigin:r,signer:c?.publicKey},u=new AbortController;return e.channelId||e.sendPayloadToProvider({rid:n,signal:u.signal}).catch(I=>u.abort(I)),await e.onClientAuthorizationCallback(_,u.signal,await e.getDeviceSignature(),e.channelId)}var C="https://auth.revibase.com";var Nt="revibase.com";var wi="device-keys",L="ed25519-keys",St="private-key",Ct="public-key",v=class e{static openDB(){return new Promise((t,n)=>{let r=indexedDB.open(wi,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(L)||o.createObjectStore(L);},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error);})}static async saveToDB(t,n){let r=await e.openDB();return new Promise((o,a)=>{let i=r.transaction(L,"readwrite");i.objectStore(L).put(n,t),i.oncomplete=()=>o(),i.onerror=()=>a(i.error);})}static async loadFromDB(t){let n=await e.openDB();return new Promise((r,o)=>{let i=n.transaction(L,"readonly").objectStore(L).get(t);i.onsuccess=()=>r(i.result),i.onerror=()=>o(i.error);})}static async create(){let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",t.publicKey),r=core.convertJWKToBase64String({...n,alg:"EdDSA"});try{await e.saveToDB(St,t.privateKey);}catch(o){throw o instanceof DOMException&&o.name==="DataCloneError"?new Error("Storing device key in this browser is not supported. Try Chrome or ensure you are in a secure context."):o}return await e.saveToDB(Ct,r),r}static async getOrCreateDevicePublickey(){let t=await e.loadFromDB(Ct);return t||(t=await e.create()),{publicKey:t}}static async sign(t){let n=await e.loadFromDB(St);if(!n)throw new Error("Device key not found. Call DeviceKeyManager.create() first.");return await new jose.CompactSign(t).setProtectedHeader({alg:"EdDSA"}).sign(n)}};var Ot=class{pending=new Map;onClientAuthorizationCallback;providerOrigin;popUp=null;channelId=void 0;constructor(t){this.onClientAuthorizationCallback=t.onClientAuthorizationCallback,this.providerOrigin=t.providerOrigin??C,this.channelId=t.channelId;}async getDeviceSignature(){if(this.channelId)return {jwk:(await v.getOrCreateDevicePublickey()).publicKey,jws:await v.sign(new TextEncoder().encode(this.channelId))}}initialize(){let t=window.origin,n=S().decode(crypto.getRandomValues(new Uint8Array(16)));if(!this.channelId){let r=new URL(this.providerOrigin);if(r.searchParams.set("rid",n),r.searchParams.set("redirectOrigin",t),this.popUp=ut(r.toString()),!this.popUp)throw new Error("Popup blocked. Please enable popups.")}return {rid:n,redirectOrigin:t}}async sendPayloadToProvider({rid:t,timeoutMs:n=6e5,signal:r}){if(typeof window>"u")throw new Error("Provider can only be used in a browser environment");if(this.pending.size>0)throw new Error("An authorization flow is already in progress");return new Promise((o,a)=>{let i=setTimeout(()=>{let s=this.pending.get(t);s&&(s.cancel?s.cancel(new Error("Authentication timed out")):(this.pending.delete(t),a(new Error("Authentication timed out"))));},n);if(!this.popUp||this.popUp.closed)throw new Error("Popup is not open. Call createNewPopup() first.");this.pending.set(t,{rid:t,resolve:o,reject:a,timeoutId:i}),this.attachTransport({popup:this.popUp,origin:new URL(this.providerOrigin).origin,rid:t,signal:r});})}attachTransport(t){let{popup:n,origin:r,rid:o,signal:a}=t,i=this.pending.get(o);if(!i)return;let s=null,c=false,d=()=>{u(new Error("Aborted"));},_=()=>{a.removeEventListener("abort",d),window.removeEventListener("message",f);try{s?.close();}catch{}s=null;try{n&&!n.closed&&n.close();}catch{}this.popUp=null,clearInterval(E);},u=R=>{c||(c=true,clearTimeout(i.timeoutId),this.pending.delete(o),_(),i.reject(R));},I=()=>{c||(c=true,clearTimeout(i.timeoutId),this.pending.delete(o),_(),i.resolve({rid:o}));};if(i.cancel=u,a.aborted){u(new Error("Aborted"));return}a.addEventListener("abort",d);let E=setInterval(()=>{n?.closed&&u(new Error("Popup was closed by the user"));},2e3),f=R=>{if(R.origin!==r||R.source!==n)return;let y=R.data;!y||y.type!=="popup-connect"||y.rid!==o||R.ports?.[0]&&(s=R.ports[0],s.start(),s.postMessage({type:"popup-init"}),s.onmessage=m=>{switch(m.data.type){case "popup-complete":I();break;case "popup-error":u(new Error(m.data.error));break;case "popup-closed":{u(new Error("Lost connection with the popup."));break}}},window.removeEventListener("message",f));};window.addEventListener("message",f);}};async function Xm(e,t){let n=new Array(e.transactions.length);for(let r=0;r<e.transactions.length;r++){let{messageBytes:o}=ct().decode(k().encode(e.transactions[r])),a=await crypto.subtle.sign({name:"Ed25519"},t.keyPair.privateKey,new Uint8Array(o));n[r]=w().decode(new Uint8Array(a));}return {signatures:n}}async function ft({rid:e,privateKey:t,providerOrigin:n=C,signal:r}){let o=core.convertBase64StringToJWK(t);if(!o.alg)throw new Error("Property alg in JWK is missing.");let a=await new jose.CompactSign(k().encode(e)).setProtectedHeader({alg:o.alg}).sign(o),i=await fetch(`${n}/api/getResult`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({rid:e,signature:a}),signal:r});if(!i.ok)throw new Error((await i.json()).error);let s=i.body?.getReader();if(!s)throw new Error("Response body is not a stream");let c=new TextDecoder,d="";return new Promise((_,u)=>{let I=async()=>{try{let{done:E,value:f}=await s.read();f&&(d+=c.decode(f,{stream:!E}));let R=d.split(`
|
|
9
|
-
|
|
10
|
-
`);d=E?"":R.pop()??"";for(let y of R){let m="message",V="";for(let O of y.split(`
|
|
11
|
-
`))O.startsWith("event:")?m=O.slice(6).trim():O.startsWith("data:")&&(V=O.slice(5).trim());if(V)try{let O=JSON.parse(V);if(m==="result"){_(O);return}if(m==="error"){u(new Error(O?.error??"Unknown error"));return}}catch{}}if(E){u(new Error("Stream ended without complete result"));return}I();}catch(E){u(E instanceof Error?E:new Error(String(E)));}};I();})}async function mt(e,t=C,n=Nt){let{payload:r}=e.data;if(r.startRequest.data.type!=="message")throw new Error("Invalid request type.");let o=r.startRequest.data.payload,a=core.createMessageChallenge(o,r.client.clientOrigin,r.device.jwk,r.startRequest.rid),{verified:i}=await server.verifyAuthenticationResponse({response:r.authResponse,expectedChallenge:core.bufferToBase64URLString(a),expectedRPID:n,expectedOrigin:t,requireUserVerification:false,credential:{counter:0,id:r.authResponse.id,publicKey:core.convertPubkeyCompressedToCose(r.signer)}});if(!i)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 core.UserInfoSchema.parse({publicKey:r.signer,walletAddress:c,settingsIndexWithAddress:s,...r.additionalInfo})}async function de({privateKey:e,request:t,providerOrigin:n=C,signal:r,device:o,channelId:a}){let i=core.convertBase64StringToJWK(e);if(!i.alg)throw new Error("Property alg in JWK is missing.");let s=await new jose.CompactSign(core.createClientAuthorizationStartRequestChallenge(t)).setProtectedHeader({alg:i.alg}).sign(i),c=await fetch(`${n}/api/startRequest`,{method:"POST",body:JSON.stringify({signature:s,request:t,device:o,channelId:a}),signal:r});if(!c.ok)throw new Error((await c.json()).error);return await c.json()}async function Ep({request:e,privateKey:t,providerOrigin:n,rpId:r,signal:o,device:a,channelId:i}){let s=Qi__default.default.union([core.StartMessageRequestSchema,core.StartTransactionRequestSchema]).parse(e),{data:c,signer:d,redirectOrigin:_,rid:u}=s;c.type==="message"?await de({request:{phase:"start",redirectOrigin:_,signer:d,rid:u,validTill:Date.now()+6e5,data:{type:"message",payload:c.payload}},privateKey:t,providerOrigin:n,signal:o,device:a,channelId:i}):await de({request:{phase:"start",redirectOrigin:_,signer:d,rid:u,validTill:Date.now()+6e5,data:{type:"transaction",payload:c.payload,sendTx:true,additionalSigners:c.additionalSigners}},providerOrigin:n,privateKey:t,signal:o,device:a,channelId:i});let I=await ft({rid:u,providerOrigin:n,privateKey:t,signal:o});return I.data.type==="message"?{user:await mt({data:I.data},n,r)}:{txSig:I.data.payload.txSig,user:I.data.payload.user}}exports.RevibaseProvider=Ot;exports.createTransactionSigner=Xm;exports.executeTransaction=os;exports.processClientAuthCallback=Ep;exports.signIn=Qa;exports.transferTokens=ym;//# sourceMappingURL=index.cjs.map
|
|
8
|
+
`)}`:t}async function Xa(e){let{rid:t,redirectOrigin:n}=e.startRequest();await new Promise(i=>setTimeout(i,0));let r={phase:"start",rid:t,validTill:Date.now()+6e5,data:{type:"message",payload:ct({domain:n,nonce:N().decode(crypto.getRandomValues(new Uint8Array(16)))})},redirectOrigin:n},o=new AbortController;return e.sendPayloadToProviderViaPopup({rid:t,signal:o.signal}).catch(i=>o.abort(i)),await e.onClientAuthorizationCallback(r,o.signal,await e.getDeviceSignature(t),e.channelId)}async function Qa(e,t){let{redirectOrigin:n,rid:r}=e.startRequest();await new Promise(T=>setTimeout(T,0));let{instructions:o,signer:i,addressesByLookupTableAddress:a,hasTxManager:s=true}=t,c=core.prepareTransactionMessage({payer:m(i.walletAddress),instructions:o,addressesByLookupTableAddress:a}),d=await core.getSettingsFromIndex(i.settingsIndexWithAddress.index),_={transactionMessageBytes:N().decode(c),transactionAddress:d,transactionActionType:s?"execute":"create_with_preauthorized_execution"},u={phase:"start",rid:r,validTill:Date.now()+6e5,data:{type:"transaction",payload:_,sendTx:true,additionalSigners:t.additionalSigners},redirectOrigin:n,signer:i.publicKey},I=new AbortController;return e.sendPayloadToProviderViaPopup({rid:r,signal:I.signal}).catch(T=>I.abort(T)),await e.onClientAuthorizationCallback(u,I.signal,await e.getDeviceSignature(r),e.channelId)}var B="11111111111111111111111111111111";var ut=0,dt=1,It=2,_t=3,At=4,lt=5,Et=6,Rt=7,Tt=8;process.env.NODE_ENV!=="production"&&({[ut]:"an account with the same address already exists",[lt]:"provided address does not match addressed derived from seed",[_t]:"cannot allocate account data of this length",[It]:"cannot assign account to this program id",[At]:"length of requested seed is too long",[Rt]:"stored nonce is still in recent_blockhashes",[Et]:"advancing stored nonce requires a populated RecentBlockhashes sysvar",[Tt]:"specified nonce does not match stored nonce",[dt]:"account does not have enough SOL to perform the operation"});var ie="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";async function mm(e,t){if(t.amount<=0)throw new Error("Transfer amount must be greater than 0");if(!t.destination||typeof t.destination!="string")throw new Error("Destination address is required");let{rid:n,redirectOrigin:r}=e.startRequest();await new Promise(I=>setTimeout(I,0));let{mint:o,tokenProgram:i=ie,amount:a,destination:s,signer:c}=t,d={transactionActionType:"transfer_intent",transactionAddress:o?i:B,transactionMessageBytes:N().decode(new Uint8Array([...et().encode(a),...J().encode(m(s)),...J().encode(m(o??B))]))},_={phase:"start",rid:n,validTill:Date.now()+6e5,data:{type:"transaction",payload:d,sendTx:true},redirectOrigin:r,signer:c?.publicKey},u=new AbortController;return e.sendPayloadToProviderViaPopup({rid:n,signal:u.signal}).catch(I=>u.abort(I)),await e.onClientAuthorizationCallback(_,u.signal,await e.getDeviceSignature(n),e.channelId)}var p="https://auth.revibase.com";var gt="revibase.com";var Pi="device-keys",h="ed25519-keys",Dt="private-key",Nt="public-key",C=class e{static openDB(){return new Promise((t,n)=>{let r=indexedDB.open(Pi,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(h)||o.createObjectStore(h);},r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error);})}static async saveToDB(t,n){let r=await e.openDB();return new Promise((o,i)=>{let a=r.transaction(h,"readwrite");a.objectStore(h).put(n,t),a.oncomplete=()=>o(),a.onerror=()=>i(a.error);})}static async loadFromDB(t){let n=await e.openDB();return new Promise((r,o)=>{let a=n.transaction(h,"readonly").objectStore(h).get(t);a.onsuccess=()=>r(a.result),a.onerror=()=>o(a.error);})}static async create(){let t=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",t.publicKey),r=core.convertJWKToBase64String({...n,alg:"EdDSA"});try{await e.saveToDB(Dt,t.privateKey);}catch(o){throw o instanceof DOMException&&o.name==="DataCloneError"?new Error("Storing device key in this browser is not supported. Try Chrome or ensure you are in a secure context."):o}return await e.saveToDB(Nt,r),r}static async getOrCreateDevicePublickey(){let t=await e.loadFromDB(Nt);return t||(t=await e.create()),{publicKey:t}}static async sign(t){let n=await e.loadFromDB(Dt);if(!n)throw new Error("Device key not found. Call DeviceKeyManager.create() first.");return await new jose.CompactSign(t).setProtectedHeader({alg:"EdDSA"}).sign(n)}};var St=class{pending=new Map;onClientAuthorizationCallback;providerOrigin;popUp=null;channelId=void 0;defaultCallback=async(t,n,r,o)=>{let i=await fetch("/api/clientAuthorization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({request:t,device:r,channelId:o}),signal:n}),a=await i.json();if(!i.ok)throw new Error(a.error??"Authorization failed");return a};constructor(t,n){this.onClientAuthorizationCallback=t??this.defaultCallback,this.providerOrigin=n??p;}async getDeviceSignature(t){if(this.channelId)return {jwk:(await C.getOrCreateDevicePublickey()).publicKey,jws:await C.sign(new TextEncoder().encode(JSON.stringify({channelId:this.channelId,rid:t})))}}setChannelId(t){this.channelId=t;}async closeChannel(){let t={jwk:(await C.getOrCreateDevicePublickey()).publicKey,jws:await C.sign(new TextEncoder().encode(this.channelId))},n=await fetch(`${this.providerOrigin}/api/channel/close`,{method:"POST",body:JSON.stringify({device:t,channelId:this.channelId})});if(!n.ok){let r=await n.json();throw new Error(r.error??"Unable to close channel")}this.channelId=void 0;}startRequest(){let t=window.origin,n=N().decode(crypto.getRandomValues(new Uint8Array(16)));if(!this.channelId){let r=new URL(this.providerOrigin);if(r.searchParams.set("rid",n),r.searchParams.set("redirectOrigin",t),this.popUp=st(r.toString()),!this.popUp)throw new Error("Popup blocked. Please enable popups.")}return {rid:n,redirectOrigin:t}}async sendPayloadToProviderViaPopup({rid:t,timeoutMs:n=6e5,signal:r}){if(!this.channelId){if(typeof window>"u")throw new Error("Provider can only be used in a browser environment");if(this.pending.size>0)throw new Error("An authorization flow is already in progress");return new Promise((o,i)=>{let a=setTimeout(()=>{let s=this.pending.get(t);s&&(s.cancel?s.cancel(new Error("Authentication timed out")):(this.pending.delete(t),i(new Error("Authentication timed out"))));},n);if(!this.popUp||this.popUp.closed)throw new Error("Popup is not open. Call createNewPopup() first.");this.pending.set(t,{rid:t,resolve:o,reject:i,timeoutId:a}),this.attachTransport({popup:this.popUp,origin:new URL(this.providerOrigin).origin,rid:t,signal:r});})}}attachTransport(t){let{popup:n,origin:r,rid:o,signal:i}=t,a=this.pending.get(o);if(!a)return;let s=null,c=false,d=()=>{u(new Error("Aborted"));},_=()=>{i.removeEventListener("abort",d),window.removeEventListener("message",z);try{s?.close();}catch{}s=null;try{n&&!n.closed&&n.close();}catch{}this.popUp=null,clearInterval(T);},u=S=>{c||(c=true,clearTimeout(a.timeoutId),this.pending.delete(o),_(),a.reject(S));},I=()=>{c||(c=true,clearTimeout(a.timeoutId),this.pending.delete(o),_(),a.resolve({rid:o}));};if(a.cancel=u,i.aborted){u(new Error("Aborted"));return}i.addEventListener("abort",d);let T=setInterval(()=>{n?.closed&&u(new Error("Popup was closed by the user"));},2e3),z=S=>{if(S.origin!==r||S.source!==n)return;let w=S.data;!w||w.type!=="popup-connect"||w.rid!==o||S.ports?.[0]&&(s=S.ports[0],s.start(),s.postMessage({type:"popup-init"}),s.onmessage=se=>{switch(se.data.type){case "popup-complete":I();break;case "popup-error":u(new Error(se.data.error));break;case "popup-closed":{u(new Error("Lost connection with the popup."));break}}},window.removeEventListener("message",z));};window.addEventListener("message",z);}};async function Gm(e,t){let n=new Array(e.transactions.length);for(let r=0;r<e.transactions.length;r++){let{messageBytes:o}=at().decode(Xe().encode(e.transactions[r])),i=await crypto.subtle.sign({name:"Ed25519"},t.keyPair.privateKey,new Uint8Array(o));n[r]=v().decode(new Uint8Array(i));}return {signatures:n}}async function ae({privateKey:e,request:t,providerOrigin:n=p,signal:r,device:o,channelId:i}){let a=core.convertBase64StringToJWK(e);if(!a.alg)throw new Error("Property alg in JWK is missing.");let s=await new jose.CompactSign(core.createClientAuthorizationStartRequestChallenge(t)).setProtectedHeader({alg:a.alg}).sign(a),c=await fetch(`${n}/api/startRequest`,{method:"POST",body:JSON.stringify({signature:s,request:t,device:o,channelId:i}),signal:r});if(!c.ok)throw new Error((await c.json()).error);return await c.json()}async function Ct(e,t=p,n=gt){let{payload:r}=e.data;if(r.startRequest.data.type!=="message")throw new Error("Invalid request type.");let o=r.startRequest.data.payload,i=core.createMessageChallenge(o,r.client.clientOrigin,r.device.jwk,r.startRequest.rid),{verified:a}=await server.verifyAuthenticationResponse({response:r.authResponse,expectedChallenge:core.bufferToBase64URLString(i),expectedRPID:n,expectedOrigin:t,requireUserVerification:false,credential:{counter:0,id:r.authResponse.id,publicKey:core.convertPubkeyCompressedToCose(r.signer)}});if(!a)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 op({request:e,privateKey:t,providerOrigin:n,rpId:r,signal:o,device:i,channelId:a}){let s=Xi__default.default.union([core.StartMessageRequestSchema,core.StartTransactionRequestSchema]).parse(e),{data:c,signer:d,redirectOrigin:_,rid:u}=s;if(c.type==="message"){let T=await ae({request:{phase:"start",redirectOrigin:_,signer:d,rid:u,validTill:Date.now()+6e5,data:{type:"message",payload:c.payload}},privateKey:t,providerOrigin:n,signal:o,device:i,channelId:a});return Ct({data:T.data},n,r)}let I=await ae({request:{phase:"start",redirectOrigin:_,signer:d,rid:u,validTill:Date.now()+6e5,data:{type:"transaction",payload:c.payload,sendTx:true,additionalSigners:c.additionalSigners}},providerOrigin:n,privateKey:t,signal:o,device:i,channelId:a});return {txSig:I.data.payload.txSig,user:I.data.payload.user}}
|
|
9
|
+
exports.RevibaseProvider=St;exports.createTransactionSigner=Gm;exports.executeTransaction=Qa;exports.processClientAuthCallback=op;exports.signIn=Xa;exports.transferTokens=mm;//# sourceMappingURL=index.cjs.map
|
|
12
10
|
//# sourceMappingURL=index.cjs.map
|