nexus-sdk-hooks-events

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Hooks and Events

钩子与事件

Set up hooks once after SDK init

SDK初始化后一次性设置钩子

  • Call
    sdk.setOnIntentHook(callback)
    .
  • Call
    sdk.setOnAllowanceHook(callback)
    .
  • Call
    sdk.setOnSwapIntentHook(callback)
    .
  • If a hook is not set, the SDK auto-approves and continues.
  • If a hook is set, always call
    allow(...)
    or
    deny()
    or the flow will stall.
  • Optionally auto-deny after a timeout to avoid hanging UX.
  • 调用
    sdk.setOnIntentHook(callback)
  • 调用
    sdk.setOnAllowanceHook(callback)
  • 调用
    sdk.setOnSwapIntentHook(callback)
  • 如果未设置钩子,SDK会自动批准并继续流程。
  • 如果设置了钩子,必须调用
    allow(...)
    deny()
    ,否则流程会停滞。
  • 可选择在超时后自动拒绝,以避免用户体验卡顿。

Handle intent hook (bridge / bridgeAndTransfer / bridgeAndExecute)

处理intent钩子(bridge / bridgeAndTransfer / bridgeAndExecute)

Signature

签名

ts
sdk.setOnIntentHook((data) => {
  // data: OnIntentHookData
});
ts
sdk.setOnIntentHook((data) => {
  // data: OnIntentHookData
});

OnIntentHookData

OnIntentHookData

  • allow(): void
    — continue the flow
  • deny(): void
    — reject the flow
  • intent: ReadableIntent
    — readable intent info for UI
  • refresh(selectedSources?: number[]): Promise<ReadableIntent>
    — refresh the intent
  • allow(): void
    — 继续流程
  • deny(): void
    — 拒绝流程
  • intent: ReadableIntent
    — 用于UI的可读intent信息
  • refresh(selectedSources?: number[]): Promise<ReadableIntent>
    — 刷新intent

How to use

使用方法

  • Store
    data
    in a ref so UI can call
    allow()
    /
    deny()
    later.
  • Call
    refresh()
    on an interval (e.g., every 15s) if you show intent details.
  • If the user closes the modal or cancels, call
    deny()
    and clear the ref.
  • data
    存储在ref中,以便UI后续调用
    allow()
    /
    deny()
  • 如果展示intent详情,按固定间隔(例如每15秒)调用
    refresh()
  • 如果用户关闭弹窗或取消操作,调用
    deny()
    并清空ref。

Handle allowance hook (approval control)

处理授权钩子(审批控制)

Signature

签名

ts
sdk.setOnAllowanceHook((data) => {
  // data: OnAllowanceHookData
});
ts
sdk.setOnAllowanceHook((data) => {
  // data: OnAllowanceHookData
});

OnAllowanceHookData

OnAllowanceHookData

  • allow(decisions): void
    • decisions
      must match the number of
      sources
    • each entry can be
      'min'
      ,
      'max'
      ,
      bigint
      , or numeric string
  • deny(): void
  • sources: AllowanceHookSources
    • includes chain/token info and current vs required allowance
  • allow(decisions): void
    • decisions
      的数量必须与
      sources
      一致
    • 每个条目可以是
      'min'
      'max'
      、bigint或数字字符串
  • deny(): void
  • sources: AllowanceHookSources
    • 包含链/代币信息以及当前与所需的授权额度

How to use

使用方法

  • Present each source to the user (chain + token + required allowance).
  • Build the
    decisions
    array in the same order as
    sources
    .
  • Call
    allow(decisions)
    to continue, or
    deny()
    to cancel.
  • Ensure
    decisions.length === sources.length
    or the SDK will reject with
    INVALID_VALUES_ALLOWANCE_HOOK
    .
  • 向用户展示每个来源(链 + 代币 + 所需授权额度)。
  • 按照
    sources
    的顺序构建
    decisions
    数组。
  • 调用
    allow(decisions)
    继续流程,或调用
    deny()
    取消。
  • 确保
    decisions.length === sources.length
    ,否则SDK会抛出
    INVALID_VALUES_ALLOWANCE_HOOK
    错误。

Handle swap intent hook (swap flows)

处理swap intent钩子(swap流程)

Signature

签名

ts
sdk.setOnSwapIntentHook((data) => {
  // data: OnSwapIntentHookData
});
ts
sdk.setOnSwapIntentHook((data) => {
  // data: OnSwapIntentHookData
});

OnSwapIntentHookData

OnSwapIntentHookData

  • allow(): void
  • deny(): void
  • intent: SwapIntent
  • refresh(): Promise<SwapIntent>
  • allow(): void
  • deny(): void
  • intent: SwapIntent
  • refresh(): Promise<SwapIntent>

How to use

使用方法

  • Store
    data
    and show a UI summary.
  • Call
    allow()
    to proceed or
    deny()
    to cancel.
  • 存储
    data
    并展示UI摘要。
  • 调用
    allow()
    继续流程或
    deny()
    取消。

Stream events for progress UI

为进度UI流式传输事件

Attach listeners

附加监听器

  • All main operations accept
    { onEvent }
    in options.
  • 所有主要操作的选项中都支持
    { onEvent }
    参数。

Event names and payloads

事件名称与负载

  • NEXUS_EVENTS.STEPS_LIST
    BridgeStepType[]
  • NEXUS_EVENTS.STEP_COMPLETE
    BridgeStepType
  • NEXUS_EVENTS.SWAP_STEP_COMPLETE
    SwapStepType
  • NEXUS_EVENTS.STEPS_LIST
    BridgeStepType[]
  • NEXUS_EVENTS.STEP_COMPLETE
    BridgeStepType
  • NEXUS_EVENTS.SWAP_STEP_COMPLETE
    SwapStepType

Typical usage

典型用法

  • Use
    STEPS_LIST
    to seed step trackers.
  • Use
    STEP_COMPLETE
    and
    SWAP_STEP_COMPLETE
    to update progress and explorer links.
  • 使用
    STEPS_LIST
    初始化步骤追踪器。
  • 使用
    STEP_COMPLETE
    SWAP_STEP_COMPLETE
    更新进度和浏览器链接。

Handle errors and cancellation

处理错误与取消

  • If an operation throws, clear intent/allowance refs to avoid stale state.
  • On user cancel, call
    deny()
    for the active hook and reset UI state.
  • If a hook is set but no
    allow()
    /
    deny()
    is called, the intent remains pending.
  • 如果操作抛出异常,清空intent/授权ref以避免状态过期。
  • 用户取消时,调用当前活跃钩子的
    deny()
    并重置UI状态。
  • 如果设置了钩子但未调用
    allow()
    /
    deny()
    ,intent会保持待处理状态。

Expand error-handling patterns

扩展错误处理模式

Normalize errors

标准化错误

  • The SDK throws
    NexusError
    for known failures.
  • Import from SDK:
    • import { NexusError, ERROR_CODES } from '@avail-project/nexus-core'
  • SDK会针对已知失败抛出
    NexusError
  • 从SDK导入:
    • import { NexusError, ERROR_CODES } from '@avail-project/nexus-core'

Map common error codes to UX responses

将常见错误码映射为UX响应

  • USER_DENIED_INTENT
    /
    USER_DENIED_ALLOWANCE
    /
    USER_DENIED_INTENT_SIGNATURE
    :
    • Treat as user cancel; show a neutral message and reset UI.
  • INVALID_VALUES_ALLOWANCE_HOOK
    :
    • Fix
      decisions
      length/type and resubmit.
  • SDK_NOT_INITIALIZED
    /
    WALLET_NOT_CONNECTED
    /
    CONNECT_ACCOUNT_FAILED
    :
    • Prompt user to reconnect; re-run
      sdk.initialize(...)
      .
  • INVALID_INPUT
    /
    INVALID_ADDRESS_LENGTH
    :
    • Validate inputs; block submission until fixed.
  • INSUFFICIENT_BALANCE
    /
    NO_BALANCE_FOR_ADDRESS
    :
    • Prompt user to reduce amount or fund source chain.
  • TOKEN_NOT_SUPPORTED
    /
    CHAIN_NOT_FOUND
    :
    • Block submission and update selectors.
  • QUOTE_FAILED
    /
    SWAP_FAILED
    /
    RATES_CHANGED_BEYOND_TOLERANCE
    /
    SLIPPAGE_EXCEEDED_ALLOWANCE
    :
    • Re-run quote or suggest a smaller amount.
  • RFF_FEE_EXPIRED
    :
    • Re-simulate and re-submit the transaction.
  • TRANSACTION_TIMEOUT
    /
    LIQUIDITY_TIMEOUT
    :
    • Show “pending” state and allow retry or check intent history.
  • TRANSACTION_REVERTED
    :
    • Display failure with explorer link if available.
  • COSMOS_ERROR
    /
    INTERNAL_ERROR
    :
    • Show a generic error and log
      err.data?.details
      for support.
  • USER_DENIED_INTENT
    /
    USER_DENIED_ALLOWANCE
    /
    USER_DENIED_INTENT_SIGNATURE
    :
    • 视为用户取消;展示中性提示并重置UI。
  • INVALID_VALUES_ALLOWANCE_HOOK
    :
    • 修正
      decisions
      的长度/类型后重新提交。
  • SDK_NOT_INITIALIZED
    /
    WALLET_NOT_CONNECTED
    /
    CONNECT_ACCOUNT_FAILED
    :
    • 提示用户重新连接;重新运行
      sdk.initialize(...)
  • INVALID_INPUT
    /
    INVALID_ADDRESS_LENGTH
    :
    • 验证输入;修复前阻止提交。
  • INSUFFICIENT_BALANCE
    /
    NO_BALANCE_FOR_ADDRESS
    :
    • 提示用户减少金额或为源链充值。
  • TOKEN_NOT_SUPPORTED
    /
    CHAIN_NOT_FOUND
    :
    • 阻止提交并更新选择器。
  • QUOTE_FAILED
    /
    SWAP_FAILED
    /
    RATES_CHANGED_BEYOND_TOLERANCE
    /
    SLIPPAGE_EXCEEDED_ALLOWANCE
    :
    • 重新获取报价或建议减少金额。
  • RFF_FEE_EXPIRED
    :
    • 重新模拟并重新提交交易。
  • TRANSACTION_TIMEOUT
    /
    LIQUIDITY_TIMEOUT
    :
    • 展示“待处理”状态,允许重试或查看intent历史。
  • TRANSACTION_REVERTED
    :
    • 展示失败信息,若有则提供浏览器链接。
  • COSMOS_ERROR
    /
    INTERNAL_ERROR
    :
    • 展示通用错误信息,并记录
      err.data?.details
      用于支持服务。

Use a helper pattern

使用助手模式

ts
import { NexusError, ERROR_CODES } from '@avail-project/nexus-core';

export function getReadableNexusError(err: unknown): string {
  if (err instanceof NexusError) {
    switch (err.code) {
      case ERROR_CODES.USER_DENIED_INTENT:
      case ERROR_CODES.USER_DENIED_ALLOWANCE:
      case ERROR_CODES.USER_DENIED_INTENT_SIGNATURE:
        return 'Transaction cancelled by user';
      case ERROR_CODES.INSUFFICIENT_BALANCE:
        return 'Insufficient balance';
      case ERROR_CODES.SLIPPAGE_EXCEEDED_ALLOWANCE:
      case ERROR_CODES.RATES_CHANGED_BEYOND_TOLERANCE:
        return 'Price changed too much. Please try again.';
      case ERROR_CODES.TRANSACTION_TIMEOUT:
        return 'Transaction timed out. Please retry.';
      default:
        return err.message;
    }
  }
  if (err instanceof Error) return err.message;
  return 'Unknown error';
}
ts
import { NexusError, ERROR_CODES } from '@avail-project/nexus-core';

export function getReadableNexusError(err: unknown): string {
  if (err instanceof NexusError) {
    switch (err.code) {
      case ERROR_CODES.USER_DENIED_INTENT:
      case ERROR_CODES.USER_DENIED_ALLOWANCE:
      case ERROR_CODES.USER_DENIED_INTENT_SIGNATURE:
        return 'Transaction cancelled by user';
      case ERROR_CODES.INSUFFICIENT_BALANCE:
        return 'Insufficient balance';
      case ERROR_CODES.SLIPPAGE_EXCEEDED_ALLOWANCE:
      case ERROR_CODES.RATES_CHANGED_BEYOND_TOLERANCE:
        return 'Price changed too much. Please try again.';
      case ERROR_CODES.TRANSACTION_TIMEOUT:
        return 'Transaction timed out. Please retry.';
      default:
        return err.message;
    }
  }
  if (err instanceof Error) return err.message;
  return 'Unknown error';
}

Clean up on error

错误发生时清理

  • Clear intent/allowance refs and reset progress state:
    • intentRef.current = null; allowanceRef.current = null; swapIntentRef.current = null;
    • reset step UI and pending flags
  • 清空intent/授权ref并重置进度状态:
    • intentRef.current = null; allowanceRef.current = null; swapIntentRef.current = null;
    • 重置步骤UI和待处理标记