@bounded-sh/server 0.0.68 → 0.0.69
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 +6 -38
- package/dist/auth/providers/offchain-auth-provider.d.ts +0 -1
- package/dist/auth/providers/solana-keypair-provider.d.ts +1 -2
- package/dist/index.d.ts +1 -3
- package/dist/index.js +13 -361
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +15 -362
- package/dist/index.mjs.map +1 -1
- package/dist/wallet-client.d.ts +3 -27
- package/package.json +4 -5
- package/dist/auth/providers/evm-keypair-provider.d.ts +0 -45
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @bounded-sh/server
|
|
2
2
|
|
|
3
|
-
Server SDK for the Bounded API. It provides explicit, isolated Solana-keypair
|
|
3
|
+
Server SDK for the Bounded API. It provides explicit, isolated Solana-keypair clients for backend applications; no signer is loaded from ambient process state.
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
@@ -16,7 +16,7 @@ yarn add @bounded-sh/server
|
|
|
16
16
|
|
|
17
17
|
## Features
|
|
18
18
|
|
|
19
|
-
- Server-side authentication using Solana keypairs
|
|
19
|
+
- Server-side authentication using Solana keypairs (SIWS)
|
|
20
20
|
- In-memory session management (no cookies or local storage required)
|
|
21
21
|
- Support for all Tarobase data operations (get, getMany, set, query)
|
|
22
22
|
- Real-time subscriptions
|
|
@@ -86,27 +86,6 @@ const signature = await wallet.signMessage("Hello, world!");
|
|
|
86
86
|
// const signature = await wallet.signAndSubmitTransaction(transaction);
|
|
87
87
|
```
|
|
88
88
|
|
|
89
|
-
### EVM Keypair Client
|
|
90
|
-
|
|
91
|
-
EVM clients require a trusted RPC and deployed `BoundedRuntime` address. A write response can select only an explicitly configured chain/runtime pair, and the SDK verifies the returned `setDocuments` calldata against the requested app, paths, actions, and values before signing.
|
|
92
|
-
|
|
93
|
-
```typescript
|
|
94
|
-
import { init, createWalletClient } from '@bounded-sh/server';
|
|
95
|
-
|
|
96
|
-
await init({ appId: 'your-app-id', chain: 'base' });
|
|
97
|
-
|
|
98
|
-
const wallet = await createWalletClient({
|
|
99
|
-
evmPrivateKey: process.env.EVM_PRIVATE_KEY!,
|
|
100
|
-
chainId: 8453,
|
|
101
|
-
rpcUrl: process.env.BASE_RPC_URL!,
|
|
102
|
-
runtimeAddress: process.env.BOUNDED_RUNTIME_BASE!,
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
await wallet.set('todos/123', { text: 'Buy milk', completed: false });
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
For deliberate multi-chain use, provide `chains: { [chainId]: { rpcUrl, runtimeAddress } }`. There is no implicit RPC, runtime address, or chain switch.
|
|
109
|
-
|
|
110
89
|
### Subscriptions
|
|
111
90
|
|
|
112
91
|
```typescript
|
|
@@ -138,16 +117,7 @@ function getWebhookKeysUrl(): string | undefined;
|
|
|
138
117
|
### Authentication
|
|
139
118
|
|
|
140
119
|
```typescript
|
|
141
|
-
function createWalletClient(options:
|
|
142
|
-
| { keypair: string }
|
|
143
|
-
| {
|
|
144
|
-
evmPrivateKey: string;
|
|
145
|
-
chainId: number;
|
|
146
|
-
rpcUrl?: string;
|
|
147
|
-
runtimeAddress?: string;
|
|
148
|
-
chains?: Record<string, { rpcUrl: string; runtimeAddress: string; name?: string }>;
|
|
149
|
-
}
|
|
150
|
-
): Promise<WalletClient>;
|
|
120
|
+
function createWalletClient(options: { keypair: string }): Promise<WalletClient>;
|
|
151
121
|
function getAuthProvider(): Promise<AuthProvider>; // always rejects; no process-global provider
|
|
152
122
|
function getIdToken(): Promise<string | null>; // always rejects; no process-global session
|
|
153
123
|
```
|
|
@@ -182,15 +152,13 @@ class SolanaKeypairProvider implements AuthProvider {
|
|
|
182
152
|
login(): Promise<User | null>;
|
|
183
153
|
logout(): Promise<void>;
|
|
184
154
|
signMessage(message: string): Promise<string>;
|
|
185
|
-
runTransaction(evmTransactionData?: EVMTransaction, solTransactionData?: SolTransaction, options?: SetOptions): Promise<TransactionResult>;
|
|
186
155
|
restoreSession(): Promise<User | null>;
|
|
187
156
|
getNativeMethods(): Promise<any>;
|
|
188
157
|
}
|
|
189
158
|
```
|
|
190
159
|
|
|
191
|
-
`
|
|
192
|
-
|
|
193
|
-
networks fail closed.
|
|
160
|
+
`signAndSubmitTransaction` requires an explicit provider `rpcUrl`; a missing RPC
|
|
161
|
+
fails closed.
|
|
194
162
|
|
|
195
163
|
## Types
|
|
196
164
|
|
|
@@ -242,7 +210,7 @@ Please see the main repository for contribution guidelines.
|
|
|
242
210
|
|
|
243
211
|
This server-side SDK differs from the web SDK in several important ways:
|
|
244
212
|
|
|
245
|
-
1. **Authentication Method**: Uses explicit Solana
|
|
213
|
+
1. **Authentication Method**: Uses explicit Solana keys instead of browser wallets
|
|
246
214
|
2. **Storage Strategy**: Uses in-memory storage instead of localStorage/sessionStorage
|
|
247
215
|
3. **Environment**: Optimized for Node.js/backend environments rather than browsers
|
|
248
216
|
4. **Session Management**: Does not rely on browser-specific APIs
|
|
@@ -18,5 +18,4 @@ export declare class OffchainAuthProvider implements AuthProvider {
|
|
|
18
18
|
* for the full implementation with blockhash handling and feePayer support.
|
|
19
19
|
*/
|
|
20
20
|
signAndSubmitTransaction(_transaction: Transaction | VersionedTransaction, _feePayer?: any): Promise<string>;
|
|
21
|
-
runTransaction(evmTransactionData?: any, solTransactionData?: any, options?: any): Promise<any>;
|
|
22
21
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Keypair, Transaction, VersionedTransaction } from '@solana/web3.js';
|
|
2
2
|
import * as anchor from '@coral-xyz/anchor';
|
|
3
|
-
import type { AuthProvider,
|
|
3
|
+
import type { AuthProvider, User } from '@bounded-sh/core';
|
|
4
4
|
export declare class SolanaKeypairProvider implements AuthProvider {
|
|
5
5
|
private readonly rpcUrl;
|
|
6
6
|
private readonly serverKeypair;
|
|
@@ -32,7 +32,6 @@ export declare class SolanaKeypairProvider implements AuthProvider {
|
|
|
32
32
|
*/
|
|
33
33
|
private submitAndConfirmTransaction;
|
|
34
34
|
private getRpcUrl;
|
|
35
|
-
runTransaction(_evmTransactionData?: EVMTransaction, _solTransactionData?: SolTransaction, _options?: SetOptions): Promise<TransactionResult>;
|
|
36
35
|
getNativeMethods(): Promise<{
|
|
37
36
|
keypair: Keypair;
|
|
38
37
|
}>;
|
package/dist/index.d.ts
CHANGED
|
@@ -5,12 +5,10 @@ export type { BoundedDecline, DeclineReason, DeclineBoundary } from '@bounded-sh
|
|
|
5
5
|
export { getAuthProvider } from './auth';
|
|
6
6
|
export { get, getMany, set, setMany, setFile, getFiles, search, queryAggregate, runQuery, runQueryMany, runExpression, runExpressionMany, signMessage, signTransaction, signAndSubmitTransaction, count, aggregate, subscribe, functions, invokeFunction, live, liveIntent, liveStatus, } from './explicit-client-only';
|
|
7
7
|
export { reconcileSetResult, waitForSetResult } from '@bounded-sh/core';
|
|
8
|
-
export type { SetResult, SetEntry, SetDocuments, MirrorSync, SolanaFence,
|
|
8
|
+
export type { SetResult, SetEntry, SetDocuments, MirrorSync, SolanaFence, ChainTag, SolanaChainTag, CommittedSetResult, ConfirmedSetResult, SolanaConfirmedSetResult, SubmittedSetResult, SolanaSubmittedSetResult, SolanaExpiredNotLandedSetResult, SolanaSignedSetResult, TransactionResult, TransactionReconciliation, ReconcileSetResultOptions, WaitForSetResultOptions, FileUploadResult, FileDeleteResult, } from '@bounded-sh/core';
|
|
9
9
|
export type { AuthProvider, ClientConfig, User, GetOptions, SearchOptions, SetOptions, CountOptions, AggregateOptions, AggregateOperation, AggregateResult, AggregateSpec, AggregateRow, QueryAggregateOptions, GetManyResult, RunExpressionOptions, RunExpressionResult, RequestOverrides, RunQueryOptions, InvokeOptions, LiveIntentOptions, LiveStatus, LiveStatusOptions, } from '@bounded-sh/core';
|
|
10
10
|
export { getIdToken } from './utils';
|
|
11
11
|
export { createWalletClient, WalletClient } from './wallet-client';
|
|
12
12
|
export type { CreateWalletClientOptions } from './wallet-client';
|
|
13
|
-
export { EvmKeypairProvider } from './auth/providers/evm-keypair-provider';
|
|
14
|
-
export type { EvmKeypairChainConfig } from './auth/providers/evm-keypair-provider';
|
|
15
13
|
export { verifyWebhook, clearWebhookKeyCache, clearWebhookReplayCache, WebhookVerificationError, DEFAULT_WEBHOOK_KEYS_URL, InMemoryReplayStore, } from './webhooks';
|
|
16
14
|
export type { WebhookPayload, WebhookPublicKey, WebhookOperation, VerifyWebhookOptions, WebhookHeaders, WebhookReplayStore, } from './webhooks';
|
package/dist/index.js
CHANGED
|
@@ -5,8 +5,6 @@ var web3_js = require('@solana/web3.js');
|
|
|
5
5
|
var bs58 = require('bs58');
|
|
6
6
|
var buffer = require('buffer');
|
|
7
7
|
var nacl = require('tweetnacl');
|
|
8
|
-
var viem = require('viem');
|
|
9
|
-
var accounts = require('viem/accounts');
|
|
10
8
|
|
|
11
9
|
async function init(newConfig) {
|
|
12
10
|
await core.init(Object.assign(Object.assign({}, newConfig), { authProvider: null, isServer: true, skipBackendInit: true }));
|
|
@@ -212,16 +210,6 @@ class SolanaKeypairProvider {
|
|
|
212
210
|
}
|
|
213
211
|
throw new Error('Solana RPC URL is required for server keypair transaction submission; pass an explicit rpcUrl when creating SolanaKeypairProvider.');
|
|
214
212
|
}
|
|
215
|
-
/* ----------------------------------------------------------- *
|
|
216
|
-
* Transaction runner
|
|
217
|
-
* ----------------------------------------------------------- */
|
|
218
|
-
async runTransaction(_evmTransactionData, _solTransactionData, _options) {
|
|
219
|
-
// Client-side Solana transaction building is retired: the realtime worker
|
|
220
|
-
// returns a fully-built (and, when sponsored, partially-signed) transaction
|
|
221
|
-
// on its 202, which the SDK validates and signs via signTransaction /
|
|
222
|
-
// signAndSubmitTransaction. This provider serves no EVM payload either.
|
|
223
|
-
throw new Error('runTransaction is not supported by this provider; Bounded returns pre-built Solana transactions that are signed with signTransaction/signAndSubmitTransaction.');
|
|
224
|
-
}
|
|
225
213
|
async getNativeMethods() {
|
|
226
214
|
return { keypair: this.keypair };
|
|
227
215
|
}
|
|
@@ -260,314 +248,6 @@ class OffchainAuthProvider {
|
|
|
260
248
|
async signAndSubmitTransaction(_transaction, _feePayer) {
|
|
261
249
|
throw new Error('Poofnet does not support real Solana transactions. Deploy your project to mainnet to use this feature.');
|
|
262
250
|
}
|
|
263
|
-
async runTransaction(evmTransactionData, solTransactionData, options) {
|
|
264
|
-
return this.wrappedProvider.runTransaction(evmTransactionData, solTransactionData, options);
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
function evmErrorText(error) {
|
|
269
|
-
const message = error === null || error === void 0 ? void 0 : error.message;
|
|
270
|
-
return typeof message === 'string' && message.length > 0 ? message : String(error);
|
|
271
|
-
}
|
|
272
|
-
/**
|
|
273
|
-
* Whether a broadcast failure PROVES the transaction never entered the network.
|
|
274
|
-
* A node-level validation rejection is definitive and keeps throwing; a
|
|
275
|
-
* transport failure (timeout, socket reset, aborted request) is ambiguous — the
|
|
276
|
-
* node may hold the bytes — and must resolve as `submitted`.
|
|
277
|
-
*
|
|
278
|
-
* "already known"/"already imported" is deliberately NOT definitive: it means
|
|
279
|
-
* the node already has these exact bytes, which is success, not failure.
|
|
280
|
-
*/
|
|
281
|
-
const DEFINITIVE_EVM_SEND_MARKERS = [
|
|
282
|
-
'nonce too low',
|
|
283
|
-
'insufficient funds',
|
|
284
|
-
'intrinsic gas too low',
|
|
285
|
-
'gas required exceeds',
|
|
286
|
-
'exceeds block gas limit',
|
|
287
|
-
'invalid sender',
|
|
288
|
-
'invalid signature',
|
|
289
|
-
'execution reverted',
|
|
290
|
-
'transaction underpriced',
|
|
291
|
-
'oversized data',
|
|
292
|
-
];
|
|
293
|
-
function isDefinitiveEvmSendFailure(error) {
|
|
294
|
-
var _a, _b;
|
|
295
|
-
const message = String((_b = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error) !== null && _b !== void 0 ? _b : '').toLowerCase();
|
|
296
|
-
if (!message)
|
|
297
|
-
return false;
|
|
298
|
-
if (message.includes('already known') || message.includes('already imported'))
|
|
299
|
-
return false;
|
|
300
|
-
return DEFINITIVE_EVM_SEND_MARKERS.some(marker => message.includes(marker));
|
|
301
|
-
}
|
|
302
|
-
/** viem raises a dedicated not-found error when a receipt simply is not mined yet. */
|
|
303
|
-
function isReceiptNotFound(error) {
|
|
304
|
-
var _a, _b;
|
|
305
|
-
const name = String((_a = error === null || error === void 0 ? void 0 : error.name) !== null && _a !== void 0 ? _a : '');
|
|
306
|
-
if (name === 'TransactionReceiptNotFoundError')
|
|
307
|
-
return true;
|
|
308
|
-
return String((_b = error === null || error === void 0 ? void 0 : error.message) !== null && _b !== void 0 ? _b : '').toLowerCase().includes('could not be found');
|
|
309
|
-
}
|
|
310
|
-
const NO_SOLANA = 'An EVM keypair client cannot sign Solana transactions.';
|
|
311
|
-
function normalizeChainConfig(input) {
|
|
312
|
-
var _a;
|
|
313
|
-
if (!Number.isSafeInteger(input.chainId) || input.chainId <= 0)
|
|
314
|
-
throw new Error('EVM chainId must be a positive safe integer');
|
|
315
|
-
let rpc;
|
|
316
|
-
try {
|
|
317
|
-
rpc = new URL(input.rpcUrl);
|
|
318
|
-
}
|
|
319
|
-
catch (_b) {
|
|
320
|
-
throw new Error(`EVM RPC URL is invalid for chain ${input.chainId}`);
|
|
321
|
-
}
|
|
322
|
-
if (rpc.protocol !== 'https:' && !(rpc.protocol === 'http:' && (rpc.hostname === 'localhost' || rpc.hostname === '127.0.0.1' || rpc.hostname === '[::1]'))) {
|
|
323
|
-
throw new Error(`EVM RPC URL must use HTTPS for chain ${input.chainId}`);
|
|
324
|
-
}
|
|
325
|
-
const runtimeAddress = core.normalizeEvmAddress(input.runtimeAddress);
|
|
326
|
-
if (!runtimeAddress)
|
|
327
|
-
throw new Error(`BoundedRuntime address is invalid for chain ${input.chainId}`);
|
|
328
|
-
return { chainId: input.chainId, rpcUrl: rpc.toString(), runtimeAddress, name: ((_a = input.name) === null || _a === void 0 ? void 0 : _a.trim()) || `EVM ${input.chainId}` };
|
|
329
|
-
}
|
|
330
|
-
function asViemChain(config) {
|
|
331
|
-
return viem.defineChain({
|
|
332
|
-
id: config.chainId,
|
|
333
|
-
name: config.name,
|
|
334
|
-
nativeCurrency: { name: 'Native token', symbol: 'NATIVE', decimals: 18 },
|
|
335
|
-
rpcUrls: { default: { http: [config.rpcUrl] } },
|
|
336
|
-
});
|
|
337
|
-
}
|
|
338
|
-
class EvmKeypairProvider {
|
|
339
|
-
constructor(privateKey, defaultChainId, chainConfigs) {
|
|
340
|
-
this.chains = new Map();
|
|
341
|
-
if (!/^0x[0-9a-fA-F]{64}$/.test(privateKey))
|
|
342
|
-
throw new Error('Invalid EVM private key: expected 0x followed by 64 hex characters.');
|
|
343
|
-
this.account = accounts.privateKeyToAccount(privateKey);
|
|
344
|
-
const address = core.normalizeEvmAddress(this.account.address);
|
|
345
|
-
if (!address)
|
|
346
|
-
throw new Error('Could not derive a valid EVM address from the private key');
|
|
347
|
-
this.address = address;
|
|
348
|
-
for (const raw of chainConfigs) {
|
|
349
|
-
const chain = normalizeChainConfig(raw);
|
|
350
|
-
if (this.chains.has(chain.chainId))
|
|
351
|
-
throw new Error(`Duplicate EVM chain configuration: ${chain.chainId}`);
|
|
352
|
-
this.chains.set(chain.chainId, chain);
|
|
353
|
-
}
|
|
354
|
-
if (!this.chains.has(defaultChainId))
|
|
355
|
-
throw new Error(`Default EVM chain ${defaultChainId} is not configured`);
|
|
356
|
-
this.defaultChainId = defaultChainId;
|
|
357
|
-
}
|
|
358
|
-
user() {
|
|
359
|
-
// @user.address (the Solana wallet) is null for an EVM keypair login: this
|
|
360
|
-
// principal has only an EVM address. User.address is typed `string | null`.
|
|
361
|
-
return { id: this.address, address: null, evmAddress: this.address, provider: this };
|
|
362
|
-
}
|
|
363
|
-
async createBoundedSession(sessionConfig) {
|
|
364
|
-
var _a, _b, _c, _d;
|
|
365
|
-
// Bind the SIWE nonce/message/session to the snapshotted app+issuer when a
|
|
366
|
-
// wallet client supplies one, so a later global init() cannot retarget this
|
|
367
|
-
// session mint (CTA-05); otherwise read the mutable global init() config.
|
|
368
|
-
const nonce = await core.genAuthNonce(sessionConfig);
|
|
369
|
-
const appId = (_a = sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.appId) !== null && _a !== void 0 ? _a : (await core.getConfig()).appId;
|
|
370
|
-
const message = core.genSiweMessage(this.address, nonce, appId, 'server', 'https://server/login', { chainId: this.defaultChainId });
|
|
371
|
-
const signature = await this.account.signMessage({ message });
|
|
372
|
-
const session = await core.createSessionWithSignature(this.address, message, signature, 'siwe', sessionConfig);
|
|
373
|
-
return {
|
|
374
|
-
address: this.address,
|
|
375
|
-
accessToken: String((_b = session.accessToken) !== null && _b !== void 0 ? _b : ''),
|
|
376
|
-
idToken: String((_c = session.idToken) !== null && _c !== void 0 ? _c : ''),
|
|
377
|
-
refreshToken: String((_d = session.refreshToken) !== null && _d !== void 0 ? _d : ''),
|
|
378
|
-
};
|
|
379
|
-
}
|
|
380
|
-
async login() { return this.user(); }
|
|
381
|
-
async restoreSession() { return this.user(); }
|
|
382
|
-
async logout() { }
|
|
383
|
-
async signMessage(message) {
|
|
384
|
-
return this.account.signMessage({ message });
|
|
385
|
-
}
|
|
386
|
-
async signTransaction(_transaction) {
|
|
387
|
-
throw new Error(NO_SOLANA);
|
|
388
|
-
}
|
|
389
|
-
async signAndSubmitTransaction(_transaction, _feePayer) {
|
|
390
|
-
throw new Error(NO_SOLANA);
|
|
391
|
-
}
|
|
392
|
-
async runTransaction(evm, sol, options) {
|
|
393
|
-
var _a;
|
|
394
|
-
if (evm && sol)
|
|
395
|
-
throw new Error('A transaction cannot target EVM and Solana at the same time.');
|
|
396
|
-
if (!evm || !evm.chainId || !evm.to || !evm.data)
|
|
397
|
-
throw new Error('A complete EVM transaction is required');
|
|
398
|
-
if ((options === null || options === void 0 ? void 0 : options.shouldSubmitTx) === false)
|
|
399
|
-
throw new Error('EVM keypair writes submit atomically; shouldSubmitTx:false is unsupported.');
|
|
400
|
-
const config = this.chains.get(evm.chainId);
|
|
401
|
-
if (!config)
|
|
402
|
-
throw new Error(`EVM chain ${evm.chainId} is not configured for this wallet client`);
|
|
403
|
-
if (core.normalizeEvmAddress(evm.to) !== config.runtimeAddress)
|
|
404
|
-
throw new Error('EVM transaction target is not the configured BoundedRuntime');
|
|
405
|
-
if (evm.nonce !== undefined)
|
|
406
|
-
throw new Error('Server-supplied EVM nonces are not accepted');
|
|
407
|
-
try {
|
|
408
|
-
if (BigInt((_a = evm.value) !== null && _a !== void 0 ? _a : '0') !== BigInt(0))
|
|
409
|
-
throw new Error('BoundedRuntime.setDocuments cannot transfer native value');
|
|
410
|
-
}
|
|
411
|
-
catch (error) {
|
|
412
|
-
if (error instanceof Error && error.message.includes('cannot transfer'))
|
|
413
|
-
throw error;
|
|
414
|
-
throw new Error('Invalid EVM transaction value');
|
|
415
|
-
}
|
|
416
|
-
// The shared decoder accepts only canonical ordinary/attested document
|
|
417
|
-
// writes and rejects selector-prefix smuggling, aliases and trailing bytes.
|
|
418
|
-
core.assertCanonicalBoundedRuntimeWriteCalldata(evm.data);
|
|
419
|
-
// A server key can safely switch between explicitly configured chains: each
|
|
420
|
-
// tx selects its own immutable viem client/RPC/runtime tuple. No untrusted
|
|
421
|
-
// server response may introduce a new chain or RPC endpoint.
|
|
422
|
-
const chain = asViemChain(config);
|
|
423
|
-
const transport = viem.http(config.rpcUrl);
|
|
424
|
-
const wallet = viem.createWalletClient({ account: this.account, chain, transport });
|
|
425
|
-
const publicClient = viem.createPublicClient({ chain, transport });
|
|
426
|
-
// Unlike a browser wallet this provider OWNS the private key, so it prepares
|
|
427
|
-
// and signs locally with an EXPLICIT nonce and derives the hash before the
|
|
428
|
-
// transaction is ever broadcast. Learning the hash only from
|
|
429
|
-
// `sendTransaction()` discards an identifier we could have known, so an
|
|
430
|
-
// accepted-but-lost response would strand a landed write.
|
|
431
|
-
let request;
|
|
432
|
-
let signedTransaction;
|
|
433
|
-
let hash;
|
|
434
|
-
let nonce;
|
|
435
|
-
try {
|
|
436
|
-
request = await wallet.prepareTransactionRequest({
|
|
437
|
-
account: this.account,
|
|
438
|
-
chain,
|
|
439
|
-
to: config.runtimeAddress,
|
|
440
|
-
data: evm.data,
|
|
441
|
-
value: BigInt(0),
|
|
442
|
-
});
|
|
443
|
-
nonce = Number(request.nonce);
|
|
444
|
-
if (!Number.isSafeInteger(nonce) || nonce < 0)
|
|
445
|
-
throw new Error('the prepared transaction carries no usable nonce');
|
|
446
|
-
signedTransaction = await wallet.signTransaction(request);
|
|
447
|
-
hash = viem.keccak256(signedTransaction);
|
|
448
|
-
}
|
|
449
|
-
catch (error) {
|
|
450
|
-
// Preparation and local signing happen entirely before broadcast, so any
|
|
451
|
-
// failure here is definitive.
|
|
452
|
-
throw error;
|
|
453
|
-
}
|
|
454
|
-
const fence = {
|
|
455
|
-
chainId: config.chainId,
|
|
456
|
-
sender: this.address,
|
|
457
|
-
nonce,
|
|
458
|
-
signedTransaction,
|
|
459
|
-
};
|
|
460
|
-
try {
|
|
461
|
-
await publicClient.sendRawTransaction({ serializedTransaction: signedTransaction });
|
|
462
|
-
}
|
|
463
|
-
catch (error) {
|
|
464
|
-
if (isDefinitiveEvmSendFailure(error))
|
|
465
|
-
throw error;
|
|
466
|
-
// Ambiguous transport outcome: the node may already hold these exact
|
|
467
|
-
// bytes. Report the pre-derived hash and the fence so reconciliation can
|
|
468
|
-
// poll it, or rebroadcast the byte-identical bytes while the nonce is
|
|
469
|
-
// unused — which cannot produce a second execution.
|
|
470
|
-
return {
|
|
471
|
-
outcome: 'submitted',
|
|
472
|
-
lane: 'evm',
|
|
473
|
-
transactionSignature: hash,
|
|
474
|
-
fence,
|
|
475
|
-
reason: `Broadcast response was lost or inconclusive: ${evmErrorText(error)}`,
|
|
476
|
-
};
|
|
477
|
-
}
|
|
478
|
-
let receipt;
|
|
479
|
-
try {
|
|
480
|
-
receipt = await publicClient.waitForTransactionReceipt({ hash });
|
|
481
|
-
}
|
|
482
|
-
catch (error) {
|
|
483
|
-
// The bytes were accepted; only the confirmation outcome is unknown.
|
|
484
|
-
return {
|
|
485
|
-
outcome: 'submitted',
|
|
486
|
-
lane: 'evm',
|
|
487
|
-
transactionSignature: hash,
|
|
488
|
-
fence,
|
|
489
|
-
reason: `Confirmation outcome unknown: ${evmErrorText(error)}`,
|
|
490
|
-
};
|
|
491
|
-
}
|
|
492
|
-
if (receipt.status !== 'success')
|
|
493
|
-
throw new Error(`EVM transaction ${hash} reverted on-chain`);
|
|
494
|
-
if (receipt.blockNumber > BigInt(Number.MAX_SAFE_INTEGER))
|
|
495
|
-
throw new Error('EVM receipt block number exceeds the SDK safe-integer range');
|
|
496
|
-
return {
|
|
497
|
-
outcome: 'confirmed',
|
|
498
|
-
lane: 'evm',
|
|
499
|
-
transactionSignature: hash,
|
|
500
|
-
blockNumber: Number(receipt.blockNumber),
|
|
501
|
-
gasUsed: receipt.gasUsed.toString(),
|
|
502
|
-
data: receipt,
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
/**
|
|
506
|
-
* Poll the SAME hash, and — only while the fenced nonce is still unused — put
|
|
507
|
-
* the byte-identical signed transaction back on the wire. Same nonce, same
|
|
508
|
-
* signature, so a rebroadcast can never produce a second execution.
|
|
509
|
-
*
|
|
510
|
-
* It NEVER reports a retry-safe terminal state. Nonce advancement is not proof
|
|
511
|
-
* the write did not execute: a replacement can occupy the same sender and
|
|
512
|
-
* nonce carrying identical Bounded calldata under a different hash, and plain
|
|
513
|
-
* JSON-RPC offers no transaction-by-sender-and-nonce lookup to identify it.
|
|
514
|
-
*/
|
|
515
|
-
async reconcileEvmTransaction(request) {
|
|
516
|
-
var _a, _b;
|
|
517
|
-
const chainId = (_b = (_a = request.fence) === null || _a === void 0 ? void 0 : _a.chainId) !== null && _b !== void 0 ? _b : this.defaultChainId;
|
|
518
|
-
const config = this.chains.get(chainId);
|
|
519
|
-
if (!config)
|
|
520
|
-
return { state: 'unknown', reason: `EVM chain ${chainId} is not configured for this wallet client` };
|
|
521
|
-
const chain = asViemChain(config);
|
|
522
|
-
const transport = viem.http(config.rpcUrl);
|
|
523
|
-
const publicClient = viem.createPublicClient({ chain, transport });
|
|
524
|
-
try {
|
|
525
|
-
const receipt = await publicClient.getTransactionReceipt({ hash: request.transactionHash });
|
|
526
|
-
if (receipt) {
|
|
527
|
-
if (receipt.status !== 'success') {
|
|
528
|
-
return { state: 'failed', reason: `EVM transaction ${request.transactionHash} reverted on-chain` };
|
|
529
|
-
}
|
|
530
|
-
if (receipt.blockNumber > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
531
|
-
return { state: 'unknown', reason: 'EVM receipt block number exceeds the SDK safe-integer range' };
|
|
532
|
-
}
|
|
533
|
-
return { state: 'confirmed', blockNumber: Number(receipt.blockNumber) };
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
catch (error) {
|
|
537
|
-
// viem throws `TransactionReceiptNotFoundError` when it is simply not
|
|
538
|
-
// mined yet; that is not an error condition, just "still unknown".
|
|
539
|
-
if (!isReceiptNotFound(error)) {
|
|
540
|
-
return { state: 'unknown', reason: `receipt lookup failed: ${evmErrorText(error)}` };
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
const fence = request.fence;
|
|
544
|
-
if (!request.allowRebroadcast || !fence) {
|
|
545
|
-
return { state: 'unknown', reason: 'no receipt yet for this transaction hash' };
|
|
546
|
-
}
|
|
547
|
-
try {
|
|
548
|
-
const nonceNow = await publicClient.getTransactionCount({ address: fence.sender, blockTag: 'latest' });
|
|
549
|
-
if (nonceNow > fence.nonce) {
|
|
550
|
-
// The nonce is spent. It may have been spent by THIS transaction under a
|
|
551
|
-
// different hash (a replacement), so this is emphatically not retry-safe.
|
|
552
|
-
return {
|
|
553
|
-
state: 'unknown',
|
|
554
|
-
reason: `nonce ${fence.nonce} on ${fence.sender} has been consumed but this hash has no receipt; ` +
|
|
555
|
-
'the transaction may have been replaced, so the write is not proven absent',
|
|
556
|
-
};
|
|
557
|
-
}
|
|
558
|
-
await publicClient.sendRawTransaction({ serializedTransaction: fence.signedTransaction });
|
|
559
|
-
return { state: 'unknown', reason: 'rebroadcast the byte-identical fenced transaction; still awaiting a receipt' };
|
|
560
|
-
}
|
|
561
|
-
catch (error) {
|
|
562
|
-
return { state: 'unknown', reason: `rebroadcast attempt was inconclusive: ${evmErrorText(error)}` };
|
|
563
|
-
}
|
|
564
|
-
}
|
|
565
|
-
async getNativeMethods() { return this.account; }
|
|
566
|
-
transactionPolicy() {
|
|
567
|
-
return {
|
|
568
|
-
runtimeAddresses: Object.fromEntries([...this.chains].map(([id, config]) => [String(id), config.runtimeAddress])),
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
251
|
}
|
|
572
252
|
|
|
573
253
|
// #023: strip caller-supplied auth headers so an operation runs as the isolated wallet, not
|
|
@@ -627,12 +307,11 @@ function jwtExpiringSoon(token) {
|
|
|
627
307
|
/* WalletClient */
|
|
628
308
|
/* ------------------------------------------------------------------ */
|
|
629
309
|
class WalletClient {
|
|
630
|
-
constructor(provider, sessionManager, address, config
|
|
310
|
+
constructor(provider, sessionManager, address, config) {
|
|
631
311
|
this.provider = provider;
|
|
632
312
|
this.sessionManager = sessionManager;
|
|
633
313
|
this.address = address;
|
|
634
314
|
this.config = config;
|
|
635
|
-
this.evmTransactionPolicy = evmTransactionPolicy;
|
|
636
315
|
this.live = {
|
|
637
316
|
intent: (roomPath, intent, opts = {}) => core.live.intent(roomPath, intent, this.mergeLiveIntentOptions(opts)),
|
|
638
317
|
// Route status through the SAME auth merge intent uses so a server-keypair
|
|
@@ -665,10 +344,12 @@ class WalletClient {
|
|
|
665
344
|
}
|
|
666
345
|
/* ---- Auth override helpers ---- */
|
|
667
346
|
buildOverrides() {
|
|
668
|
-
return
|
|
347
|
+
return {
|
|
348
|
+
authProvider: this.provider,
|
|
669
349
|
// Pin every request to this wallet client's snapshotted app + endpoints so
|
|
670
350
|
// a later global init() can never retarget its reads/writes (CTA-05).
|
|
671
|
-
_config: this.config,
|
|
351
|
+
_config: this.config,
|
|
352
|
+
_getAuthHeaders: async () => {
|
|
672
353
|
let s = await this.sessionManager.getSession();
|
|
673
354
|
// Keypair-backed session: if the cached token is expired/near-expiry,
|
|
674
355
|
// re-sign for a fresh one (we always hold the key). Keeps long-lived WS
|
|
@@ -679,9 +360,12 @@ class WalletClient {
|
|
|
679
360
|
s = await this.sessionManager.getSession();
|
|
680
361
|
}
|
|
681
362
|
return { Authorization: `Bearer ${s.idToken}` };
|
|
682
|
-
},
|
|
363
|
+
},
|
|
364
|
+
_clearAuth: async () => {
|
|
683
365
|
this.sessionManager.clearSession();
|
|
684
|
-
},
|
|
366
|
+
},
|
|
367
|
+
_walletAddress: this.address,
|
|
368
|
+
};
|
|
685
369
|
}
|
|
686
370
|
/** #023: strip caller Authorization (any casing) so operations run as the isolated wallet. */
|
|
687
371
|
sanitizeHeaders(headers) {
|
|
@@ -690,7 +374,7 @@ class WalletClient {
|
|
|
690
374
|
mergeSetOverrides(opts) {
|
|
691
375
|
var _a;
|
|
692
376
|
const ovr = this.buildOverrides();
|
|
693
|
-
return Object.assign(Object.assign({}, opts), { _overrides: Object.assign(Object.assign({}, opts === null || opts === void 0 ? void 0 : opts._overrides), { headers: this.sanitizeHeaders((_a = opts === null || opts === void 0 ? void 0 : opts._overrides) === null || _a === void 0 ? void 0 : _a.headers), authProvider: ovr.authProvider, _getAuthHeaders: ovr._getAuthHeaders, _clearAuth: ovr._clearAuth,
|
|
377
|
+
return Object.assign(Object.assign({}, opts), { _overrides: Object.assign(Object.assign({}, opts === null || opts === void 0 ? void 0 : opts._overrides), { headers: this.sanitizeHeaders((_a = opts === null || opts === void 0 ? void 0 : opts._overrides) === null || _a === void 0 ? void 0 : _a.headers), authProvider: ovr.authProvider, _getAuthHeaders: ovr._getAuthHeaders, _clearAuth: ovr._clearAuth, _config: ovr._config }) });
|
|
694
378
|
}
|
|
695
379
|
mergeReadOverrides(existing) {
|
|
696
380
|
const ovr = this.buildOverrides();
|
|
@@ -809,20 +493,13 @@ class WalletClient {
|
|
|
809
493
|
}
|
|
810
494
|
}
|
|
811
495
|
/**
|
|
812
|
-
* Create a self-contained wallet client bound to one Solana
|
|
496
|
+
* Create a self-contained wallet client bound to one Solana keypair.
|
|
813
497
|
* Each client has its own auth session — no global state is mutated.
|
|
814
498
|
*
|
|
815
499
|
* @example
|
|
816
500
|
* ```ts
|
|
817
501
|
* const vault = await createWalletClient({ keypair: process.env.VAULT_KEY });
|
|
818
502
|
* await vault.set('markets/123', data);
|
|
819
|
-
*
|
|
820
|
-
* const evmVault = await createWalletClient({
|
|
821
|
-
* evmPrivateKey: process.env.EVM_PRIVATE_KEY,
|
|
822
|
-
* chainId: 8453,
|
|
823
|
-
* rpcUrl: process.env.BASE_RPC_URL,
|
|
824
|
-
* runtimeAddress: process.env.BOUNDED_RUNTIME,
|
|
825
|
-
* });
|
|
826
503
|
* ```
|
|
827
504
|
*/
|
|
828
505
|
async function createWalletClient(opts) {
|
|
@@ -838,32 +515,8 @@ async function createWalletClient(opts) {
|
|
|
838
515
|
authApiUrl: config.authApiUrl,
|
|
839
516
|
authMethod: config.authMethod,
|
|
840
517
|
};
|
|
841
|
-
if ('evmPrivateKey' in opts && typeof opts.evmPrivateKey === 'string') {
|
|
842
|
-
const chainConfigs = [];
|
|
843
|
-
if (opts.chains) {
|
|
844
|
-
for (const [rawId, chain] of Object.entries(opts.chains)) {
|
|
845
|
-
const chainId = Number(rawId);
|
|
846
|
-
if (!Number.isSafeInteger(chainId) || chainId <= 0)
|
|
847
|
-
throw new Error(`Invalid EVM chain id in chains map: ${rawId}`);
|
|
848
|
-
chainConfigs.push({ chainId, rpcUrl: chain.rpcUrl, runtimeAddress: chain.runtimeAddress, name: chain.name });
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
if (opts.rpcUrl !== undefined || opts.runtimeAddress !== undefined) {
|
|
852
|
-
if (!opts.rpcUrl || !opts.runtimeAddress)
|
|
853
|
-
throw new Error('Single-chain EVM clients require both rpcUrl and runtimeAddress');
|
|
854
|
-
if (chainConfigs.some((chain) => chain.chainId === opts.chainId))
|
|
855
|
-
throw new Error(`EVM chain ${opts.chainId} is configured twice`);
|
|
856
|
-
chainConfigs.push({ chainId: opts.chainId, rpcUrl: opts.rpcUrl, runtimeAddress: opts.runtimeAddress });
|
|
857
|
-
}
|
|
858
|
-
if (chainConfigs.length === 0)
|
|
859
|
-
throw new Error('EVM wallet clients require an explicit RPC URL and BoundedRuntime address');
|
|
860
|
-
const provider = new EvmKeypairProvider(opts.evmPrivateKey, opts.chainId, chainConfigs);
|
|
861
|
-
const sessionManager = core.ServerSessionManager.forSessionFactory(() => provider.createBoundedSession(sessionConfig));
|
|
862
|
-
await sessionManager.getSession();
|
|
863
|
-
return new WalletClient(provider, sessionManager, provider.address, config, provider.transactionPolicy());
|
|
864
|
-
}
|
|
865
518
|
if (!('keypair' in opts) || typeof opts.keypair !== 'string') {
|
|
866
|
-
throw new Error('createWalletClient requires
|
|
519
|
+
throw new Error('createWalletClient requires a Solana keypair');
|
|
867
520
|
}
|
|
868
521
|
const kp = parseKeypair(opts.keypair);
|
|
869
522
|
let provider = new SolanaKeypairProvider((_a = config.rpcUrl) !== null && _a !== void 0 ? _a : null, kp);
|
|
@@ -1242,7 +895,6 @@ Object.defineProperty(exports, "waitForSetResult", {
|
|
|
1242
895
|
get: function () { return core.waitForSetResult; }
|
|
1243
896
|
});
|
|
1244
897
|
exports.DEFAULT_WEBHOOK_KEYS_URL = DEFAULT_WEBHOOK_KEYS_URL;
|
|
1245
|
-
exports.EvmKeypairProvider = EvmKeypairProvider;
|
|
1246
898
|
exports.InMemoryReplayStore = InMemoryReplayStore;
|
|
1247
899
|
exports.WalletClient = WalletClient;
|
|
1248
900
|
exports.WebhookVerificationError = WebhookVerificationError;
|