CKB KeyWayDocs

React SDK

Provider, hooks and components for authentication, CKB accounts and the user's Fiber node.

Provider

<KeyWayProvider appId="keyway_..." appName="Your app" theme="light" fiberNode="hosted">
  <App />
</KeyWayProvider>
PropDefaultPurpose
appIdnonePublic application ID. Requests require a registered origin.
appNameCKB KeyWayName shown in KeyWay's dialogs. Not the email sender or subject.
themelightLight or dark dialogs.
fiberNodehostedWhere the user's Fiber node runs: hosted on KeyWay's servers, or browser in this page.
autoStartFiberfalseStart Fiber as soon as the user signs in. Account recovery is always automatic.
joyIdReturnPaththe current pageWhere JoyID returns on a cross-origin isolated page (JoyID backups). A path on your site that renders KeyWayProvider.
approveFiberChannelOpenbuilt-in dialogYour own approval for opening a channel. Receives FiberChannelOpenPreview.
approveFiberChannelClosebuilt-in dialogYour own approval for closing a channel. Receives FiberChannelClosePreview.
approveFiberPeerConnectbuilt-in dialogYour own approval for connecting to or disconnecting from a peer. Receives FiberPeerPreview.
approveFiberChannelSettingsbuilt-in dialogYour own approval for changing a channel's forwarding settings. Receives FiberChannelSettingsPreview.
approveFiberPaymentnoneYour own confirmation for Fiber payments, which have no built-in dialog. Receives FiberPaymentPreview.
approveCkbTransactionbuilt-in dialogYour own approval for signer transactions. Receives the decoded TransactionPreview.
approveCkbMessagebuilt-in dialogYour own approval for message signing. Receives MessagePreview.
approveRecoverybuilt-in dialogYour own approval for turning account recovery on. Receives RecoveryPreview.
approveBackupChangebuilt-in dialogYour own approval for adding or removing a recovery backup. Receives BackupChangePreview.
onErrornoneAccount recovery, Fiber startup and device lease errors.
onFiberStartupnoneEach step of starting the Fiber node, with elapsed time.

Every approval prop returns true to go ahead or false to cancel, or a promise of either. The emailed-code prompt is always KeyWay's own. It shows the address the code went to, checks the code while staying open, and lets the user send a new one.

After the user approves in a built-in dialog, the dialog stays open with a busy button until the next step is ready (the code prompt, or the action finishing), and shows the reason if that step fails. The dialogs keep keyboard focus while open and return it to the element that opened them.

onFiberStartup receives { stage, at, elapsedMs }. A browser node goes through loading_account, claiming_device, restoring_channels (only when restoring a backup), starting_browser_node, connecting_peer, synchronizing and ready. A hosted node goes through loading_account, starting_hosted_node, synchronizing and ready.

Authentication: useKeyWay()

const { ready, authenticated, user, login, logout } = useKeyWay();

ready means session validation finished, not that the account or Fiber is ready. user.id is the stable user ID. login() opens the sign-in dialog. logout() revokes the session; a running browser node first backs up its channel state. A hosted node stays online.

Account: useCkbWallet()

const { status, signer, address, legacyAddress, publicKey, balance, refreshing, refreshBalance, error, recovery } = useCkbWallet();
MemberBehavior
statusdisconnected (signed out), loading, ready or error.
signerA CCC signer for the account once it's ready. See Signing transactions.
addressThe account's CKB testnet address. It changes once if the user turns on account recovery.
legacyAddressThe address from before recovery was turned on, if it was.
publicKeyThe account's compressed secp256k1 public key.
balanceOn-chain CKB in shannons, as a bigint. Undefined until the first read completes.
refreshBalance()Reads the balance again. Doesn't need Fiber.
errorAn account loading error, or a balance error once the account is ready. A balance error doesn't invalidate the account.
recoveryOpt-in account recovery: status, backups, enable(), addBackup(), removeBackup(), createEvmBackup(), createJoyIdBackup(). See Account address & recovery.

Fiber: useFiber()

const {
  status, fiberNode, startupStage, start, stop, node,
  channels, refreshChannels, openChannel, closeChannel,
  createInvoice, getInvoice, parseInvoice, estimatePayment, payInvoice, error,
} = useFiber();
MemberBehavior
statusstopped, starting, running or error. Running doesn't imply a funded channel.
fiberNodehosted or browser, from the provider.
startupStageThe current step while the node starts.
start()Starts a browser node, or connects to the user's hosted node. Doesn't fund a channel.
stop()Stops a browser node, or disconnects from a hosted node, which stays online. Doesn't close channels.
nodeThe user's Fiber node with Fiber's own method names, once status is running. See Fiber node.
channelsThe user's open channels with canSend, canReceive, capacity and asset, refreshed every ten seconds while running.
refreshChannels()Reads channels now and updates channels.
openChannel(options?, onProgress?)Opens a CKB or token channel after the user approves it, waits until it's ready, and refreshes. Options: fundingAmount, udtTypeScript, peer, public, fundingFeeRate, commitmentFeeRate.
closeChannel(id, options?)Closes a channel after the user approves it. Options: force, feeRate. On-chain settlement follows.
createInvoice(params)Creates an invoice. currency defaults to Fibt and expiry to 24 hours.
getInvoice(params) / parseInvoice(params)Reads an invoice's status, or decodes one.
estimatePayment(params)Checks the route and fee for a payment without sending it. Returns { routable: true, fee } or { routable: false, error }.
payInvoice(invoice, options?)Pays, waits for the payment to succeed, and refreshes. Rejects if it fails.
errorA startup or channel-listing error. Calls also reject, so catch them.

See Fiber payments for examples.

Components

KeyWayLoginButton signs the user in or out. Labels: loginLabel, logoutLabel, pendingLabel.

KeyWayFiberButton starts or stops Fiber, and asks the user to sign in first if needed. Labels: startLabel, stopLabel, startingLabel.

<KeyWayFiberButton startLabel="Start payments" stopLabel="Stop" startingLabel="Starting…" />

Both accept every other <button> prop.

Silent signing

Each approval prop replaces KeyWay's dialog with your app's answer. An app that returns true signs without showing a dialog. This one signs plain CKB transfers of up to 100 CKB silently and cancels anything else:

<KeyWayProvider
  appId="keyway_..."
  approveCkbTransaction={(preview) =>
    Number(preview.sendingCkb) <= 100 &&
    // No cell with a type script: no tokens, NFTs, Nervos DAO or other contracts.
    [...preview.details.inputs, ...preview.details.outputs].every((cell) => !cell.type)
  }
>
  <App />
</KeyWayProvider>

Any approval prop works this way: approveCkbTransaction, approveCkbMessage, approveFiberChannelOpen, approveFiberChannelClose, approveFiberPeerConnect, approveFiberChannelSettings, approveRecovery and approveBackupChange. Fiber payments have no dialog by default.

These always appear, whatever your app returns:

  • Sign-in, and the emailed sign-in code.
  • The emailed code once what leaves the account in 24 hours reaches the user's daily amount, if they set one.
  • The emailed code for turning recovery on, adding a backup and removing one.
  • The emailed code for loosening email confirmation, such as raising or removing a daily amount.

Silent signing moves the user's confirmation into your app. Your app becomes responsible for showing the user what they approve, so only do it for flows the user has already agreed to, such as a purchase they just confirmed in your own interface, and prefer checking the preview over returning true unconditionally. KeyWay's server still applies its own checks: fee and rate limits, the daily amounts and the emailed code.

Other exports

The package also exports the KeyWaySigner class, the FIBER_METHODS table, KeyWayError, toKeyWayError() and friendlyKeyWayError(), and the preview, approval, channel and node types used above. Backend code and credentials are not part of the package.

On this page