CKB KeyWayDocs

Fiber payments

Open a channel, read balances, create invoices, and send payments.

Use useFiber() for channels and payments. Start the user's Fiber node before using them.

const fiber = useFiber();
await fiber.start();

fiber.status is "stopped", "starting", "running" or "error". Running doesn't imply a funded channel. For every Fiber method under its official name, see Fiber node.

Open a channel

A Fiber channel locks funds on-chain and makes them available for off-chain payments. CKB amounts use shannons: 1 CKB = 100,000,000 shannons.

const SHANNONS_PER_CKB = 100_000_000n;

const { channelId } = await fiber.openChannel(
  { fundingAmount: 1_000n * SHANNONS_PER_CKB, public: true },
  (stage) => console.log(stage),
);

// Resolves after the channel is ready.

fundingAmount defaults to 1,000 CKB. Pass peer with a Fiber node ID to choose the channel peer; otherwise KeyWay picks an available public testnet peer. The progress callback receives connecting, negotiating, confirming, signing, broadcasting and waiting.

The channel is funded from the user's CKB account, and KeyWay sets its close address to that same account. Channel funding counts toward the user's email-confirmation total, and past their daily amount it needs the emailed code.

Open a token channel

Pass the token's type script as udtTypeScript, with fundingAmount in the token's smallest unit. The peer must accept the token; on testnet, Fiber's public peers accept RUSD. A token channel also locks some CKB as a reserve, which the dialog shows.

const info = await fiber.node!.nodeInfo();
const rusd = info.udt_cfg_infos.find((token) => token.name === "RUSD")?.script;
if (!rusd) throw new Error("This node doesn't accept RUSD");

await fiber.openChannel({
  udtTypeScript: rusd,
  fundingAmount: 21n * 100_000_000n, // 21 RUSD (8 decimals)
});

Approve the channel opening

KeyWay shows a built-in dialog before it signs the funding transaction, with the amount, any token and CKB reserve, the peer and the network fee. To use your own interface, pass approveFiberChannelOpen to KeyWayProvider:

<KeyWayProvider
  appId="keyway_..."
  approveFiberChannelOpen={async (preview) => {
    // preview: FiberChannelOpenPreview
    return openYourConfirmationScreen(preview.token?.amountText ?? `${preview.amountCkb} CKB`, preview.feeCkb);
  }}
>
  <App />
</KeyWayProvider>

The callback runs after KeyWay has built and checked the exact funding transaction, and before it is signed. Return true to sign or false to cancel.

On the user's first channel, preview.feeReserveCkb is set too: approving also sends a one-time 62 CKB fee reserve to the user's own Fiber node, so it can claim their funds after a force close. Show it in your dialog. See Closing channels.

Read channels and balances

const account = useCkbWallet();
const onchainShannons = account.balance;

const ckbChannels = fiber.channels.filter(
  (channel) => channel.status === "ready" && channel.asset.kind === "ckb",
);

const fiberShannons = ckbChannels.reduce((total, channel) => total + channel.canSend, 0n);

Each channel has:

FieldMeaning
id, peerThe channel ID and the peer's Fiber node ID.
statuspending, ready, closing, closed, failed or unknown.
asset{ kind: "ckb" }, or { kind: "token", typeScript } for a token channel.
canSendWhat the user can still send, in the asset's smallest unit.
canReceiveWhat the user can still receive.
capacityThe channel's size: canSend plus canReceive.
publicWhether the channel is announced to the network.
rawFiber's own channel object.

fiber.channels refreshes every ten seconds while the node runs; call refreshChannels() to read it now. Reserves, in-flight payments and route liquidity can limit what is payable at a given moment.

Create an invoice

function toHex(value: bigint): `0x${string}` {
  return `0x${value.toString(16)}`;
}

// Fiber invoice expiry is in seconds.
const INVOICE_EXPIRY_SECONDS = 60n * 60n;

const created = await fiber.createInvoice({
  amount: toHex(1n * SHANNONS_PER_CKB),
  description: "Order 42",
  expiry: toHex(INVOICE_EXPIRY_SECONDS),
});

console.log(created.invoice_address);

currency defaults to Fibt, Fiber's testnet currency. expiry is a hex string of seconds and defaults to 24 hours (0x15180). For a token invoice, add udt_type_script. Read an invoice's status with getInvoice({ payment_hash }), or decode one with parseInvoice({ invoice }).

Pay an invoice

Check that a route exists, and what it costs, before paying:

const estimate = await fiber.estimatePayment({
  invoice,
  max_fee_amount: toHex(1n * SHANNONS_PER_CKB),
});

if (!estimate.routable) {
  console.log(estimate.error.code, estimate.error.retryable);
  throw estimate.error;
}

console.log(`Fee: ${estimate.fee} shannons`);
const settled = await fiber.payInvoice(invoice, {
  max_fee_amount: toHex(1n * SHANNONS_PER_CKB),
});

// Resolves after the payment succeeds; rejects if it fails.

Payments have no built-in dialog, because Fiber is for fast payments. Show your own confirmation before calling payInvoice, or pass approveFiberPayment to KeyWayProvider so every payment from the node goes through it; see Fiber node.

With a hosted node, payments count toward the user's 24-hour email-confirmation total, and KeyWay asks for the emailed code once that total reaches the user's daily amount. Browser-node payments aren't counted; see Fiber node. A hosted sendPayment pays at most the fee its preview estimated, which is what counts toward the total (or your max_fee_amount when that is lower); limit the fee with max_fee_amount, since max_fee_rate is refused there. If the route costs more by the time the payment is sent, the payment fails and can be tried again.

The sender doesn't need a direct channel to the receiver. Fiber uses its public channel graph to find a route whose channels have enough liquidity.

A newly opened public channel may need time to propagate through Fiber gossip before other nodes can route through it.

Close a channel

await fiber.closeChannel(channelId);

KeyWay shows a close dialog first, with what returns to the user; replace it with approveFiberChannelClose. A normal (cooperative) close returns the user's side to their own address once the closing transaction confirms.

closeChannel(channelId, { force: true }) closes without the peer and settles after about 4 hours. Fiber 0.10.1 settles force-closed channels to the node's own key, and KeyWay currently sweeps those settlements to the user's address; see Closing channels. Prefer a cooperative close whenever the peer is online.

Stop Fiber

Call stop() from useFiber() to stop using Fiber in this page. In browser mode it stops the node. A hosted node stays online on KeyWay's servers. Neither closes channels.

const { stop } = useFiber();
await stop();

On this page