-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathChannel.ts
More file actions
786 lines (706 loc) · 25.5 KB
/
Channel.ts
File metadata and controls
786 lines (706 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
import {
Contract,
FeeBumpTransaction,
Keypair,
Transaction,
TransactionBuilder,
nativeToScVal,
rpc,
} from '@stellar/stellar-sdk'
import { Method, Receipt, Store } from 'mppx'
import {
DEFAULT_DECIMALS,
NETWORK_PASSPHRASE,
SOROBAN_RPC_URLS,
type NetworkId,
} from '../../constants.js'
import { toBaseUnits } from '../../Methods.js'
import { resolveKeypair } from '../../signers.js'
import { channel as ChannelMethod } from '../Methods.js'
import { getChannelState, type ChannelState } from './State.js'
/**
* Creates a Stellar one-way-channel method for use on the **server**.
*
* The server:
* 1. Issues challenges with the channel contract address and cumulative amount
* 2. Verifies commitment signatures against the channel's commitment key
* 3. Optionally closes the channel and settles funds on-chain
*
* @example
* ```ts
* import { stellar } from 'stellar-mpp-sdk/channel/server'
* import { Mppx } from 'mppx/server'
*
* const mppx = Mppx.create({
* secretKey: 'my-secret',
* methods: [
* stellar.channel({
* channel: 'C...', // on-chain channel contract
* commitmentKey: 'GABC...', // ed25519 public key for verifying commitments
* }),
* ],
* })
* ```
*/
export function channel(parameters: channel.Parameters) {
const {
channel: channelAddress,
checkOnChainState = false,
commitmentKey: commitmentKeyParam,
decimals = DEFAULT_DECIMALS,
feeBumpSigner: feeBumpSignerParam,
network = 'testnet',
onDisputeDetected,
rpcUrl,
signer: signerParam,
sourceAccount,
store,
} = parameters
const resolvedRpcUrl = rpcUrl ?? SOROBAN_RPC_URLS[network]
const networkPassphrase = NETWORK_PASSPHRASE[network]
const server = new rpc.Server(resolvedRpcUrl)
// Parse the commitment public key (accepts G... Stellar public key string or Keypair)
const commitmentKeypair = (() => {
if (typeof commitmentKeyParam === 'string') {
return Keypair.fromPublicKey(commitmentKeyParam)
}
return commitmentKeyParam
})()
const signerKeypair = signerParam ? resolveKeypair(signerParam) : undefined
const feeBumpKeypair = feeBumpSignerParam
? resolveKeypair(feeBumpSignerParam)
: undefined
// Track cumulative amounts per channel in the store
const cumulativeKey = `stellar:channel:cumulative:${channelAddress}`
// Serialize verify operations to prevent concurrent double-acceptance.
// Without a transactional store, two concurrent verify calls could both
// read the same cumulative amount, both pass, and only one write wins.
let verifyLock: Promise<unknown> = Promise.resolve()
return Method.toServer(ChannelMethod, {
defaults: {
channel: channelAddress,
},
async request({ request }) {
// Retrieve current cumulative amount from store
let currentCumulative = '0'
if (store) {
const stored = await store.get(cumulativeKey)
if (stored && typeof stored === 'object' && 'amount' in stored) {
currentCumulative = (stored as { amount: string }).amount
}
}
return {
...request,
amount: toBaseUnits(request.amount, decimals),
methodDetails: {
...request.methodDetails,
reference: crypto.randomUUID(),
network,
cumulativeAmount: currentCumulative,
},
}
},
async verify({ credential }) {
// Serialize through the lock to prevent concurrent double-acceptance
const result = await new Promise<any>((resolve, reject) => {
verifyLock = verifyLock.then(
() => doVerify(credential).then(resolve, reject),
() => doVerify(credential).then(resolve, reject),
)
})
return result
},
})
async function doVerify(credential: any) {
const { challenge } = credential
const { request: challengeRequest } = challenge
const payload = credential.payload
const action = payload.action ?? 'voucher'
// NM-001: Reject credentials once the channel has been finalized (closed on-chain).
// Applied to all actions including 'open'.
if (store) {
const finalized = await store.get(`stellar:channel:finalized:${channelAddress}`)
if (finalized) {
throw new ChannelVerificationError(
'Channel has been finalized. No further credentials accepted.',
{ channel: channelAddress },
)
}
}
// Replay protection — applied to all actions including 'open'.
// NM-002: The verifyLock serializes calls so the get→put gap cannot
// be exploited in a single-process deployment. Multi-process
// deployments MUST use a store with atomic put-if-absent semantics.
if (store) {
const replayKey = `stellar:challenge:${challenge.id}`
const existing = await store.get(replayKey)
if (existing) {
throw new Error('Challenge already used. Replay rejected.')
}
await store.put(replayKey, { usedAt: new Date().toISOString() })
}
// Dispatch open action to its own handler — it has completely
// different semantics (broadcasts an on-chain tx) compared to
// voucher/close which operate on existing channels.
if (action === 'open') {
return doVerifyOpen(credential)
}
// NM-001 (voucher/close): finalized and replay checks are now applied
// earlier in doVerify() for all actions including 'open'.
const commitmentAmount = BigInt(payload.amount)
const signatureHex = payload.signature
// Lazy on-chain dispute detection: if enabled, check whether
// close_start has been called on-chain. This mirrors Tempo's
// close_requested_at guard — each incoming voucher refreshes
// our view of the channel without requiring a background poller.
if (checkOnChainState) {
if (!sourceAccount) {
throw new Error(
'checkOnChainState requires sourceAccount to be set. ' +
'Provide a funded Stellar account address (G...) to use for on-chain simulations.',
)
}
try {
const state = await getChannelState({
channel: channelAddress,
network,
rpcUrl,
sourceAccount,
})
// Cache the on-chain state for the caller
if (store) {
await store.put(
`stellar:channel:state:${channelAddress}`,
{
balance: state.balance.toString(),
closeEffectiveAtLedger: state.closeEffectiveAtLedger,
currentLedger: state.currentLedger,
queriedAt: new Date().toISOString(),
},
)
}
if (state.closeEffectiveAtLedger != null) {
onDisputeDetected?.(state)
if (state.currentLedger >= state.closeEffectiveAtLedger) {
throw new ChannelVerificationError(
'Channel is closed: close effective ledger has been reached.',
{
closeEffectiveAtLedger: String(state.closeEffectiveAtLedger),
currentLedger: String(state.currentLedger),
},
)
}
}
// NM-003: Reject commitments that exceed the channel's on-chain balance.
if (commitmentAmount > state.balance) {
throw new ChannelVerificationError(
`Commitment ${commitmentAmount} exceeds channel balance ${state.balance}.`,
{
commitmentAmount: commitmentAmount.toString(),
balance: state.balance.toString(),
},
)
}
} catch (error) {
// Re-throw ChannelVerificationError (channel closed / over-balance)
if (error instanceof ChannelVerificationError) throw error
// NM-005: Fail closed — reject the voucher when the on-chain
// check cannot be completed rather than silently skipping it.
throw new ChannelVerificationError(
'On-chain state check failed. Cannot verify channel status.',
{ error: error instanceof Error ? error.message : String(error) },
)
}
}
// Validate hex signature format
if (!/^[0-9a-f]+$/i.test(signatureHex) || signatureHex.length % 2 !== 0) {
throw new ChannelVerificationError(
'Invalid signature: not a valid hex string.',
{ signature: signatureHex },
)
}
if (signatureHex.length !== 128) {
throw new ChannelVerificationError(
`Invalid signature length: expected 128 hex chars (64 bytes), got ${signatureHex.length}.`,
{ length: String(signatureHex.length) },
)
}
const signatureBytes = Buffer.from(signatureHex, 'hex')
// Retrieve the previous cumulative amount
let previousCumulative = 0n
if (store) {
const stored = await store.get(cumulativeKey)
if (stored && typeof stored === 'object' && 'amount' in stored) {
previousCumulative = BigInt((stored as { amount: string }).amount)
}
}
// Reject zero or negative requested amounts
const requestedAmount = BigInt(challengeRequest.amount)
if (requestedAmount <= 0n) {
throw new ChannelVerificationError(
'Requested amount must be positive.',
{ requestedAmount: requestedAmount.toString() },
)
}
// The new cumulative must be strictly greater than previous cumulative
if (commitmentAmount <= previousCumulative) {
throw new ChannelVerificationError(
`Commitment amount ${commitmentAmount} must be greater than previous cumulative ${previousCumulative}.`,
{
commitmentAmount: commitmentAmount.toString(),
previousCumulative: previousCumulative.toString(),
},
)
}
// The commitment must cover the requested amount
if (commitmentAmount < previousCumulative + requestedAmount) {
throw new ChannelVerificationError(
`Commitment amount ${commitmentAmount} does not cover the requested amount ${requestedAmount} (previous cumulative: ${previousCumulative}).`,
{
commitmentAmount: commitmentAmount.toString(),
requestedAmount: requestedAmount.toString(),
previousCumulative: previousCumulative.toString(),
},
)
}
// Verify: call prepare_commitment on the channel contract to
// reconstruct the expected commitment bytes, then verify the
// ed25519 signature.
const contract = new Contract(channelAddress)
const call = contract.call(
'prepare_commitment',
nativeToScVal(commitmentAmount, { type: 'i128' }),
)
const account = await server.getAccount(
sourceAccount ?? commitmentKeypair.publicKey(),
)
const simTx = new TransactionBuilder(account, {
fee: '100',
networkPassphrase,
})
.addOperation(call)
.setTimeout(30)
.build()
const simResult = await server.simulateTransaction(simTx)
if (!rpc.Api.isSimulationSuccess(simResult)) {
throw new ChannelVerificationError(
'Failed to simulate prepare_commitment for verification.',
{
error:
'error' in simResult
? String(simResult.error)
: 'unknown',
},
)
}
const returnValue = simResult.result?.retval
if (!returnValue) {
throw new ChannelVerificationError(
'prepare_commitment returned no value.',
{},
)
}
const commitmentBytes = returnValue.bytes()
// Verify the ed25519 signature
const valid = commitmentKeypair.verify(
Buffer.from(commitmentBytes),
signatureBytes,
)
if (!valid) {
throw new ChannelVerificationError(
'Commitment signature verification failed.',
{
amount: commitmentAmount.toString(),
channel: channelAddress,
},
)
}
// Update cumulative amount in store
if (store) {
await store.put(cumulativeKey, {
amount: commitmentAmount.toString(),
})
}
// Dispatch on action
if (action === 'close') {
if (!signerKeypair) {
throw new ChannelVerificationError(
'Close action requires a signer to be configured.',
{},
)
}
// Submit the close transaction on-chain
const closeOp = contract.call(
'close',
nativeToScVal(commitmentAmount, { type: 'i128' }),
nativeToScVal(Buffer.from(signatureBytes), { type: 'bytes' }),
)
const closeAccount = await server.getAccount(signerKeypair.publicKey())
const closeTx = new TransactionBuilder(closeAccount, {
fee: '100',
networkPassphrase,
})
.addOperation(closeOp)
.setTimeout(180)
.build()
const prepared = await server.prepareTransaction(closeTx)
prepared.sign(signerKeypair)
let txToSubmit: Transaction | FeeBumpTransaction = prepared
if (feeBumpKeypair) {
const MAX_FEE_BUMP = 10_000_000
const bumpFee = Math.min(Number(prepared.fee) * 10, MAX_FEE_BUMP)
txToSubmit = TransactionBuilder.buildFeeBumpTransaction(
feeBumpKeypair,
bumpFee.toString(),
prepared,
networkPassphrase,
)
txToSubmit.sign(feeBumpKeypair)
}
const sendResult = await server.sendTransaction(txToSubmit)
const MAX_POLL_ATTEMPTS = 60
let txResult = await server.getTransaction(sendResult.hash)
let attempts = 0
while (txResult.status === 'NOT_FOUND') {
if (++attempts >= MAX_POLL_ATTEMPTS) {
throw new ChannelVerificationError(
`Close transaction not found after ${MAX_POLL_ATTEMPTS} attempts.`,
{ hash: sendResult.hash },
)
}
await new Promise((r) => setTimeout(r, 1000))
txResult = await server.getTransaction(sendResult.hash)
}
if (txResult.status !== 'SUCCESS') {
throw new ChannelVerificationError(
`Close transaction failed: ${txResult.status}`,
{ hash: sendResult.hash, status: txResult.status },
)
}
// Mark channel as finalized in store
if (store) {
await store.put(`stellar:channel:finalized:${channelAddress}`, {
finalizedAt: new Date().toISOString(),
txHash: sendResult.hash,
amount: commitmentAmount.toString(),
})
}
return Receipt.from({
method: 'stellar',
reference: sendResult.hash,
status: 'success',
timestamp: new Date().toISOString(),
})
}
return Receipt.from({
method: 'stellar',
reference: challengeRequest.methodDetails?.reference ?? challenge.id,
status: 'success',
timestamp: new Date().toISOString(),
})
}
/**
* Verify an "open" credential: the client sends a signed channel-open
* transaction XDR along with an initial commitment signature. The server
* broadcasts the transaction, waits for confirmation, then initialises
* the cumulative amount in the store.
*/
async function doVerifyOpen(credential: any) {
const { challenge } = credential
const payload = credential.payload
const { transaction: txXdr, amount, signature: signatureHex } = payload
if (!txXdr || typeof txXdr !== 'string') {
throw new ChannelVerificationError(
'Open action requires a signed transaction XDR.',
{},
)
}
// Validate signature format
if (!/^[0-9a-f]+$/i.test(signatureHex) || signatureHex.length !== 128) {
throw new ChannelVerificationError(
'Invalid commitment signature for open action.',
{ length: String(signatureHex?.length ?? 0) },
)
}
const commitmentAmount = BigInt(amount)
const signatureBytes = Buffer.from(signatureHex, 'hex')
// Enforce amount invariants: both the commitment and the requested amount
// must be positive, and the commitment must cover the requested amount.
const requestedAmount = BigInt(challenge.request.amount)
if (requestedAmount <= 0n) {
throw new ChannelVerificationError(
'Open action requires a positive requested amount.',
{ requestedAmount: requestedAmount.toString() },
)
}
if (commitmentAmount <= 0n) {
throw new ChannelVerificationError(
'Open action requires a positive commitment amount.',
{ commitmentAmount: commitmentAmount.toString() },
)
}
if (commitmentAmount < requestedAmount) {
throw new ChannelVerificationError(
'Commitment amount does not cover requested amount for open action.',
{
commitmentAmount: commitmentAmount.toString(),
requestedAmount: requestedAmount.toString(),
},
)
}
// Reject if the channel is already opened (cumulativeKey already set).
if (store) {
const existing = await store.get(cumulativeKey)
if (existing) {
throw new ChannelVerificationError(
'Channel is already open. Cannot replay an open credential.',
{ channel: channelAddress },
)
}
}
// Verify the initial commitment signature via prepare_commitment simulation
const contract = new Contract(channelAddress)
const call = contract.call(
'prepare_commitment',
nativeToScVal(commitmentAmount, { type: 'i128' }),
)
const account = await server.getAccount(
sourceAccount ?? commitmentKeypair.publicKey(),
)
const simTx = new TransactionBuilder(account, {
fee: '100',
networkPassphrase,
})
.addOperation(call)
.setTimeout(30)
.build()
const simResult = await server.simulateTransaction(simTx)
if (!rpc.Api.isSimulationSuccess(simResult)) {
throw new ChannelVerificationError(
'Failed to simulate prepare_commitment for open verification.',
{
error:
'error' in simResult ? String(simResult.error) : 'unknown',
},
)
}
const returnValue = simResult.result?.retval
if (!returnValue) {
throw new ChannelVerificationError(
'prepare_commitment returned no value during open.',
{},
)
}
const commitmentBytes = returnValue.bytes()
const valid = commitmentKeypair.verify(
Buffer.from(commitmentBytes),
signatureBytes,
)
if (!valid) {
throw new ChannelVerificationError(
'Initial commitment signature verification failed.',
{ amount: commitmentAmount.toString(), channel: channelAddress },
)
}
// Parse and broadcast the open transaction
const { TransactionBuilder: TxBuilder } = await import(
'@stellar/stellar-sdk'
)
let openTx: ReturnType<typeof TxBuilder.fromXDR>
try {
openTx = TxBuilder.fromXDR(txXdr, networkPassphrase)
} catch (err) {
throw new ChannelVerificationError(
'Invalid open transaction XDR.',
{ error: err instanceof Error ? err.message : String(err) },
)
}
let txToSubmit = openTx
if (feeBumpKeypair) {
const innerTx = openTx instanceof FeeBumpTransaction
? openTx.innerTransaction
: (openTx as Transaction)
const MAX_FEE_BUMP = 10_000_000
const bumpFee = Math.min(Number(innerTx.fee) * 10, MAX_FEE_BUMP)
txToSubmit = TransactionBuilder.buildFeeBumpTransaction(
feeBumpKeypair,
bumpFee.toString(),
innerTx,
networkPassphrase,
)
;(txToSubmit as FeeBumpTransaction).sign(feeBumpKeypair)
}
const sendResult = await server.sendTransaction(txToSubmit)
const MAX_POLL_ATTEMPTS = 60
let txResult = await server.getTransaction(sendResult.hash)
let attempts = 0
while (txResult.status === 'NOT_FOUND') {
if (++attempts >= MAX_POLL_ATTEMPTS) {
throw new ChannelVerificationError(
`Open transaction not found after ${MAX_POLL_ATTEMPTS} attempts.`,
{ hash: sendResult.hash },
)
}
await new Promise((r) => setTimeout(r, 1000))
txResult = await server.getTransaction(sendResult.hash)
}
if (txResult.status !== 'SUCCESS') {
throw new ChannelVerificationError(
`Open transaction failed: ${txResult.status}`,
{ hash: sendResult.hash, status: txResult.status },
)
}
// Initialise cumulative amount in the store
if (store) {
await store.put(cumulativeKey, {
amount: commitmentAmount.toString(),
})
}
return Receipt.from({
method: 'stellar',
reference: sendResult.hash,
status: 'success',
timestamp: new Date().toISOString(),
})
}
}
/**
* Close the channel contract on-chain using a signed commitment.
* Transfers the committed amount to the recipient and auto-refunds
* the remaining balance to the funder. This is a server-side
* administrative operation.
*/
export async function close(parameters: {
/** Channel contract address. */
channel: string
/** Commitment amount to close with. */
amount: bigint
/** Ed25519 signature for the commitment. */
signature: Uint8Array
/** Keypair to sign the close transaction (source account). */
signer: Keypair
/** Optional fee bump signer. */
feeBumpSigner?: Keypair
/** Network identifier. */
network?: NetworkId
/** Custom RPC URL. */
rpcUrl?: string
}): Promise<string> {
const {
channel: channelAddress,
amount,
signature,
signer,
feeBumpSigner,
network = 'testnet',
rpcUrl,
} = parameters
const resolvedRpcUrl = rpcUrl ?? SOROBAN_RPC_URLS[network]
const networkPassphrase = NETWORK_PASSPHRASE[network]
const server = new rpc.Server(resolvedRpcUrl)
const contract = new Contract(channelAddress)
const closeOp = contract.call(
'close',
nativeToScVal(amount, { type: 'i128' }),
nativeToScVal(Buffer.from(signature), { type: 'bytes' }),
)
const account = await server.getAccount(signer.publicKey())
const tx = new TransactionBuilder(account, {
fee: '100',
networkPassphrase,
})
.addOperation(closeOp)
.setTimeout(180)
.build()
const prepared = await server.prepareTransaction(tx)
prepared.sign(signer)
let txToSubmit: Transaction | FeeBumpTransaction = prepared
if (feeBumpSigner) {
const MAX_FEE_BUMP = 10_000_000
const bumpFee = Math.min(Number(prepared.fee) * 10, MAX_FEE_BUMP)
txToSubmit = TransactionBuilder.buildFeeBumpTransaction(
feeBumpSigner,
bumpFee.toString(),
prepared,
networkPassphrase,
)
txToSubmit.sign(feeBumpSigner)
}
const result = await server.sendTransaction(txToSubmit)
const MAX_POLL_ATTEMPTS = 60
let txResult = await server.getTransaction(result.hash)
let attempts = 0
while (txResult.status === 'NOT_FOUND') {
if (++attempts >= MAX_POLL_ATTEMPTS) {
throw new ChannelVerificationError(
`Transaction not found after ${MAX_POLL_ATTEMPTS} attempts.`,
{ hash: result.hash },
)
}
await new Promise((r) => setTimeout(r, 1000))
txResult = await server.getTransaction(result.hash)
}
if (txResult.status !== 'SUCCESS') {
throw new ChannelVerificationError(
`Close transaction failed: ${txResult.status}`,
{ hash: result.hash, status: txResult.status },
)
}
return result.hash
}
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export declare namespace channel {
type Parameters = {
/** On-chain channel contract address (C...). */
channel: string
/**
* When true, each verify call lazily reads on-chain state to detect
* if `close_start` has been called (dispute detection). Requires
* `sourceAccount` to be set — a configuration error is thrown if
* `sourceAccount` is missing when this is enabled. @default false
*/
checkOnChainState?: boolean
/**
* Keypair for signing close transactions (provides sequence number).
* Required when handling close credential actions.
* Accepts a Stellar secret key string (S...) or a Keypair instance.
*/
signer?: Keypair | string
/** Optional fee bump signer for close/open transactions. */
feeBumpSigner?: Keypair | string
/**
* Ed25519 public key for verifying commitment signatures.
* Accepts a Stellar public key string (G...) or a Keypair instance.
*/
commitmentKey: string | Keypair
/** Number of decimal places for amount conversion. @default 7 */
decimals?: number
/** Stellar network. @default 'testnet' */
network?: NetworkId
/**
* Called when a dispute is detected on-chain (close_start has been called).
* Use this to trigger a close response before the waiting period elapses.
*/
onDisputeDetected?: (state: ChannelState) => void
/** Custom Soroban RPC URL. */
rpcUrl?: string
/**
* Funded Stellar account address (G...) used as the source for
* read-only transaction simulations. If omitted, the commitment
* key's public key is used, which requires it to be a funded account.
*/
sourceAccount?: string
/** Store for replay protection and cumulative amount tracking. */
store?: Store.Store
}
}
class ChannelVerificationError extends Error {
details: Record<string, string>
constructor(message: string, details: Record<string, string>) {
super(message)
this.name = 'ChannelVerificationError'
this.details = details
}
}