Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ jobs:
- run: pnpm --filter @lightninglabs/wavelength-core test
- run: pnpm --filter @lightninglabs/wavelength-web test
- run: pnpm --filter @lightninglabs/wavelength-react test
- run: pnpm --filter @lightninglabs/wavelength-react-native test
# Validate the packed packages: publint for packaging mistakes, attw for
# type/runtime resolution across consumer modes (Node ESM, bundlers).
- run: pnpm check:packages
Expand Down
113 changes: 112 additions & 1 deletion packages/core/src/base-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ class FakeClient extends BaseWavelengthClient {
params: unknown = {},
): Promise<T> {
this.calls.push({ method, params });
return Promise.resolve((this.responses.get(method) ?? {}) as T);
const response = this.responses.get(method);
if (response instanceof Error) return Promise.reject(response);
return Promise.resolve((response ?? {}) as T);
}

protected openActivityStream(opts: ActivityStreamOptions): Promise<void> {
Expand Down Expand Up @@ -224,6 +226,115 @@ describe('BaseWavelengthClient', () => {
assert.equal(result.paymentHash, 'ph');
});

describe('explicit Ark channel calls', () => {
const channelId = '01'.repeat(32);
const amountSat = 4_294_967_297; // Must survive a 32-bit boundary.
const idempotencyKey = ' promotion-1 ';
const invoice = 'ln-channel-invoice';

it('preserves the promotion amount and caller key across explicit retries', async () => {
const client = new FakeClient();
client.responses.set('promoteVTXO', {
ChannelID: channelId, Phase: 'Active', CapacitySat: amountSat,
});
for (let i = 0; i < 2; i++) {
assert.deepEqual(await client.promoteVTXO({ amountSat, idempotencyKey }), {
channelId, phase: 'Active', capacitySat: amountSat,
});
}
const call = {
method: 'promoteVTXO',
params: { AmountSat: amountSat, IdempotencyKey: idempotencyKey },
};
assert.deepEqual(client.calls, [call, call]);
});

it('dispatches the exact fee cap and returns the normalized payment proof', async () => {
const client = new FakeClient();
const paymentHash = 'ab'.repeat(32);
const preimage = 'cd'.repeat(32);
for (const feeSat of [0, 5]) {
client.responses.set('payOnActiveChannel', {
ChannelID: channelId, PaymentHash: paymentHash, Preimage: preimage,
PrivateAmountSat: amountSat, FeeSat: feeSat,
});
assert.deepEqual(await client.payOnActiveChannel({ invoice, maxFeeSat: feeSat }), {
channelId, paymentHash, preimage, privateAmountSat: amountSat, feeSat,
});
}
assert.deepEqual(client.calls, [0, 5].map((maxFeeSat) => ({
method: 'payOnActiveChannel', params: { Invoice: invoice, MaxFeeSat: maxFeeSat },
})));
});

it('issues a channel invoice and normalizes its nested activity entry', async () => {
const client = new FakeClient();
client.responses.set('receiveOnActiveChannel', {
Invoice: invoice, Entry: { ID: 'receive-1', Progress: null, Request: null },
});
const memo = 'inbound';
assert.deepEqual(await client.receiveOnActiveChannel({ amountSat, memo }), {
invoice, entry: { id: 'receive-1', progress: undefined, request: undefined },
});
assert.deepEqual(client.calls, [{
method: 'receiveOnActiveChannel', params: { AmountSat: amountSat, Memo: memo },
}]);
});

it('rejects non-JSON and inexact satoshis before dispatch', async () => {
const client = new FakeClient();
const invalid = { code: 'invalid_channel_request' };
for (const value of [-1, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1,
1n, 2n ** 63n, '123', null, undefined]) {
// Untyped hosts can pass values that TS would have rejected.
const sats = value as number;
await assert.rejects(client.promoteVTXO({ amountSat: sats, idempotencyKey }), invalid);
await assert.rejects(client.receiveOnActiveChannel({ amountSat: sats }), invalid);
await assert.rejects(client.payOnActiveChannel({ invoice, maxFeeSat: sats }), invalid);
}
await assert.rejects(client.promoteVTXO({ amountSat: 0, idempotencyKey }), invalid);
await assert.rejects(client.receiveOnActiveChannel({ amountSat: 0 }), invalid);
assert.deepEqual(client.calls, []);
});

it('requires a wire-stable caller key and a nonempty invoice', async () => {
const client = new FakeClient();
const invalid = { code: 'invalid_channel_request' };
// U+1F511 takes two JS code units but four UTF-8 bytes.
const boundaryKey = '\u{1F511}'.repeat(32);
for (const key of ['', undefined, 1, 'x'.repeat(129), boundaryKey + 'x', '\uD800']) {
await assert.rejects(client.promoteVTXO({ amountSat, idempotencyKey: key as string }), invalid);
}
await assert.rejects(client.payOnActiveChannel({ invoice: '', maxFeeSat: 0 }), invalid);
await assert.rejects(client.receiveOnActiveChannel({ amountSat, memo: 1n as never }), invalid);
assert.deepEqual(client.calls, []);
await client.promoteVTXO({ amountSat, idempotencyKey: boundaryKey });
assert.deepEqual(client.calls, [{
method: 'promoteVTXO', params: { AmountSat: amountSat, IdempotencyKey: boundaryKey },
}]);
});

it('propagates daemon and older-runtime errors without retry or fallback', async () => {
const client = new FakeClient();
const operations = {
promoteVTXO: () => client.promoteVTXO({ amountSat, idempotencyKey }),
payOnActiveChannel: () => client.payOnActiveChannel({ invoice, maxFeeSat: 0 }),
receiveOnActiveChannel: () => client.receiveOnActiveChannel({ amountSat }),
};
for (const [method, invoke] of Object.entries(operations)) {
for (const error of [
new Error('rpc error: code = FailedPrecondition desc = no liquidity'),
new WavelengthError(`unsupported facade method: ${method}`, 'unsupported_facade_method'),
]) {
client.responses.set(method, error);
client.calls.length = 0;
await assert.rejects(invoke, (err) => err === error);
assert.deepEqual(client.calls.map((call) => call.method), [method]);
}
}
});
});

it('forwards list kinds and both exit variants exactly', async () => {
const client = new FakeClient();
await client.list({ view: 'activity', kinds: ['send', 'exit'] });
Expand Down
36 changes: 32 additions & 4 deletions packages/core/src/base-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import type {
GetExitPlanRequest,
ListRequest,
OpenWalletFromPasskeyRequest,
PayOnActiveChannelRequest,
PromoteVTXORequest,
ReceiveRequest,
SendRequest,
SweepWalletRequest,
Expand All @@ -25,21 +27,26 @@ import type {
GetExitPlanResult,
ListResult,
OpenWalletFromPasskeyResult,
PayOnActiveChannelResult,
PrepareSendResult,
PromoteVTXOResult,
ReceiveResult,
SendResult,
SweepWalletResult,
UnlockWalletResult,
} from './results.ts';
import { validateRuntimeConfig, type RuntimeConfig } from './config.ts';
import type { ExternalSeedWalletClient } from './client.ts';
import type { ArkChannelClient, ExternalSeedWalletClient } from './client.ts';
import type { WavelengthEvent, WavelengthListener } from './events.ts';
import type { WalletInfo, WalletStatus } from './state.ts';
import type { FacadeMethod, ServerTransport } from './facade.ts';
import {
assertFacadeMethod,
toExternalSeedWalletStartParams,
toGoCreateWalletReq,
toGoPayOnActiveChannelReq,
toGoPromoteVTXOReq,
toGoReceiveOnActiveChannelReq,
toGoUnlockWalletReq,
toMobileConfig,
} from './facade.ts';
Expand All @@ -55,16 +62,17 @@ import {
} from './activity-options.ts';

/**
* Implements the transport-agnostic half of
* {@link ExternalSeedWalletClient}: every RPC verb is expressed in terms of
* Implements {@link ExternalSeedWalletClient} and {@link ArkChannelClient}
* across transports: every RPC verb is expressed in terms of
* the abstract invokeFacade, so a transport (web wasm, React Native gomobile,
* or a future one) supplies only the pipe: invokeFacade, ready, the
* activity-stream plumbing, and its {@link ServerTransport} flavor. The shared
* subscribe/emit listener machinery and typed wrappers live here. The facade
* catalog, public contract, native dispatch, and response normalization remain
* separate synchronization points.
*/
export abstract class BaseWavelengthClient implements ExternalSeedWalletClient {
export abstract class BaseWavelengthClient
implements ExternalSeedWalletClient, ArkChannelClient {
protected readonly listeners = new Set<WavelengthListener>();

// Serializes runtime lifecycle operations for transports that route start and
Expand Down Expand Up @@ -269,6 +277,26 @@ export abstract class BaseWavelengthClient implements ExternalSeedWalletClient {
return this.callFacade<ReceiveResult>('receive', req);
}

async promoteVTXO(req: PromoteVTXORequest): Promise<PromoteVTXOResult> {
return this.callFacade<PromoteVTXOResult>(
'promoteVTXO', toGoPromoteVTXOReq(req),
);
}

async payOnActiveChannel(
req: PayOnActiveChannelRequest,
): Promise<PayOnActiveChannelResult> {
return this.callFacade<PayOnActiveChannelResult>(
'payOnActiveChannel', toGoPayOnActiveChannelReq(req),
);
}

async receiveOnActiveChannel(req: ReceiveRequest): Promise<ReceiveResult> {
return this.callFacade<ReceiveResult>(
'receiveOnActiveChannel', toGoReceiveOnActiveChannelReq(req),
);
}

// prepareSend quotes a payment without dispatching it, returning the fee and a
// single-use sendIntentId. Pair it with sendPrepared for a quote -> confirm ->
// pay flow; send() folds the two steps into one.
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/casing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const ACRONYM_OVERRIDES: Record<string, string> = {
ID: 'id',
VTXOs: 'vtxos',
SendIntentID: 'sendIntentId',
ChannelID: 'channelId',
};

// camelKey converts one Go/PascalCase field name to camelCase. Most names just
Expand Down
25 changes: 23 additions & 2 deletions packages/core/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import type {
GetExitPlanRequest,
ListRequest,
OpenWalletFromPasskeyRequest,
PayOnActiveChannelRequest,
PromoteVTXORequest,
ReceiveRequest,
SendRequest,
SweepWalletRequest,
Expand All @@ -29,7 +31,9 @@ import type {
GetExitPlanResult,
ListResult,
OpenWalletFromPasskeyResult,
PayOnActiveChannelResult,
PrepareSendResult,
PromoteVTXOResult,
ReceiveResult,
SendResult,
SweepWalletResult,
Expand All @@ -41,8 +45,8 @@ import type {
* wraps the embedded daemon's lifecycle, wallet operations, and activity
* stream behind typed, camelCase-normalized methods.
*
* External-seed startup is an additive transport capability;
* see {@link ExternalSeedWalletClient}.
* External-seed startup and Ark channel operations are additive capabilities;
* see {@link ExternalSeedWalletClient} and {@link ArkChannelClient}.
*/
export interface WavelengthClient {
/** Resolves once the runtime assets are loaded and the client is usable. */
Expand Down Expand Up @@ -156,3 +160,20 @@ export interface ExternalSeedWalletClient extends WavelengthClient {
req: ExternalSeedWalletRequest,
): Promise<ExternalSeedWalletOpenResult>;
}

/**
* Explicit Ark channel operations on the official web and React Native clients.
* Enable them with {@link RuntimeConfig.arkChannelsEnabled} and a supporting
* runtime. Errors, including unsupported methods on older runtimes, reject
* the call. No method retries or falls back to a wallet swap.
*/
export interface ArkChannelClient extends WavelengthClient {
/** Promotes wallet funds under a caller-owned idempotency key. */
promoteVTXO(req: PromoteVTXORequest): Promise<PromoteVTXOResult>;
/** Pays a BOLT-11 invoice from outbound channel liquidity up to the fee cap. */
payOnActiveChannel(
req: PayOnActiveChannelRequest,
): Promise<PayOnActiveChannelResult>;
/** Issues an invoice for a positive amount against existing inbound liquidity. */
receiveOnActiveChannel(req: ReceiveRequest): Promise<ReceiveResult>;
}
3 changes: 3 additions & 0 deletions packages/core/src/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ describe('validateRuntimeConfig', () => {
],
['web Ark cert path', { arkServerTlsCertPath: '/tmp/ark.pem' }, 'rest'],
['web swap cert path', { swapServerTlsCertPath: '/tmp/swap.pem' }, 'rest'],
['channels without swaps', { arkChannelsEnabled: true, disableSwaps: true }, 'rest'],
['channels with btcwallet', { arkChannelsEnabled: true, walletType: 'btcwallet' }, 'grpc'],
['nonboolean channel opt-in', { arkChannelsEnabled: 'true' as never }, 'grpc'],
['fractional buffer', { bufferSize: 1.5 }, 'grpc'],
['negative workers', { signingWorkers: -1 }, 'grpc'],
['unsafe fee', { maxOperatorFeeSat: Number.MAX_SAFE_INTEGER + 1 }, 'grpc'],
Expand Down
16 changes: 16 additions & 0 deletions packages/core/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,11 @@ export type RuntimeConfig = {
swapDatabaseFileName?: string;
/** Disables Lightning swaps and omits every swap configuration field. */
disableSwaps?: boolean;
/**
* Enables explicit Ark channel operations with a supporting runtime.
* Requires the lwwallet backend and swaps. Defaults to false.
*/
arkChannelsEnabled?: boolean;
/**
* Maximum per-round operator fee the daemon accepts, in satoshis. Must be a
* nonnegative safe integer.
Expand Down Expand Up @@ -168,6 +173,17 @@ export function validateRuntimeConfig(
if (walletType !== 'lwwallet' && walletType !== 'btcwallet') {
invalidConfig(`unsupported walletType: ${String(walletType)}`);
}
if (
config.arkChannelsEnabled !== undefined &&
typeof config.arkChannelsEnabled !== 'boolean'
) {
invalidConfig('arkChannelsEnabled must be a boolean');
}
if (
config.arkChannelsEnabled && (config.disableSwaps || walletType !== 'lwwallet')
) {
invalidConfig('arkChannelsEnabled requires swaps and walletType lwwallet');
}
if (config.network === 'mainnet' && config.allowMainnet !== true) {
invalidConfig('mainnet requires allowMainnet: true');
}
Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,10 @@
* `'asset_load_failed'` cover a downloaded, verified module that fails to
* compile, which is not an asset problem and surfaces as `'wavelength_error'`
* too. `'invalid_external_seed'` means an external-seed wallet request failed
* local validation. `'runtime_active'` means the client already has a runtime
* active and must stop it before selecting another external-seed profile.
* local validation. `'invalid_channel_request'` means a typed Ark channel
* request failed validation before dispatch. `'runtime_active'` means the client
* already has a runtime active and must stop it before selecting another
* external-seed profile.
* The `(string & {})` arm keeps the union open for forward
* compatibility while still offering autocomplete on the known codes.
*/
Expand All @@ -41,6 +43,7 @@ export type WavelengthErrorCode =
| 'unsupported_facade_method'
| 'invalid_cursor'
| 'invalid_config'
| 'invalid_channel_request'
| 'invalid_external_seed'
| 'runtime_active'
| (string & {});
Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/facade.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,16 @@ describe('toMobileConfig', () => {
assert.equal(Object.hasOwn(defaulted, 'max_payment_cltv'), false);
});

it('forwards an explicit channel toggle and omits it for legacy configs', () => {
for (const transport of ['rest', 'grpc'] as const) {
for (const enabled of [true, false]) {
const config = toMobileConfig({ arkChannelsEnabled: enabled }, transport);
assert.equal(config.ark_channels_enabled, enabled);
}
assert.equal(Object.hasOwn(toMobileConfig({}, transport), 'ark_channels_enabled'), false);
}
});

it('omits every swap field when swaps are disabled', () => {
const out = toMobileConfig(
{
Expand Down
Loading
Loading