CCC Docs
    Preparing search index...

    A generic on-chain Coin (fungible token) identified by a CKB type script.

    Provides helpers for querying balances and building/completing transactions. Asset identity is defined by the complete type script (codeHash, hashType, args) — only cells with an identical type script belong to the same Coin.

    Index

    Constructors

    • Parameters

      • options: {
            script: ScriptLike;
            client: Client;
            filter?: ClientIndexerSearchKeyFilterLike | null;
            cellDeps: CellDepLike[];
        }
        • script: ScriptLike

          Type script that identifies this Coin asset.

        • client: Client

          Client used for all network requests.

        • Optionalfilter?: ClientIndexerSearchKeyFilterLike | null

          Custom indexer filter. Defaults to cells with this type script and outputDataLenRange: [16, ∞).

        • cellDeps: CellDepLike[]

          Cell deps automatically added to every built transaction.

      Returns Coin

      const coin = new Coin({
      script: { codeHash: "0x...", hashType: "type", args: "0x..." },
      client,
      cellDeps: [{ outPoint: codeOutPoint, depType: "code" }],
      });

    Properties

    script: Script

    Type script that identifies this Coin.

    client: Client
    filter: ClientIndexerSearchKeyFilter

    Indexer search filter used to find Coin cells. Defaults to cells with this type script and outputDataLenRange: [16, ∞).

    cellDeps: CellDep[]

    Cell deps required by the type script, added to every built transaction.

    Methods

    • Reads the Coin balance from raw output data without verifying the type script. Returns 0 if the data is shorter than 16 bytes.

      ⚠️ The caller must ensure the data belongs to a valid Coin cell. For safe extraction from an arbitrary cell use balanceFrom.

      Parameters

      • outputData: BytesLike

      Returns bigint

    • Aggregates Coin info (balance, capacity, count) from cells, skipping non-Coins. Accepts a single cell, a sync iterable, or an async iterable.

      Parameters

      • cells:
            | CellAnyLike
            | Iterable<CellAnyLike, any, any>
            | AsyncIterable<CellAnyLike, any, any>
      • Optionalacc: CoinInfoLike

      Returns Promise<CoinInfo>

    • Convenience wrapper around infoFrom that returns only the balance.

      Parameters

      • cells:
            | CellAnyLike
            | Iterable<CellAnyLike, any, any>
            | AsyncIterable<CellAnyLike, any, any>
      • Optionalacc: NumLike | null

      Returns Promise<bigint>

    • Scans all Coins owned by the signer and returns aggregated info.

      Parameters

      • signer: Signer
      • Optionaloptions: { source?: "chain" | "local" | null }
        • Optionalsource?: "chain" | "local" | null

          "chain" (default) queries on-chain state; "local" uses the local indexer cache which is faster but may be stale.

          ⚠️ Expensive — scales linearly with the number of Coin cells.

      Returns Promise<CoinInfo>

    • Convenience wrapper around calculateInfo that returns only the balance.

      ⚠️ Expensive — scans all Coin cells owned by the signer.

      Parameters

      • signer: Signer
      • Optionaloptions: { source?: "chain" | "local" | null }

      Returns Promise<bigint>

    • Returns whether the cell is a valid Coin for this token. Subclasses may override this to apply additional validation rules.

      Parameters

      • cellLike: CellAnyLike

      Returns Promise<boolean>

    • Returns aggregated Coin info (balance, capacity, count) for all Coin inputs in the transaction.

      Parameters

      • txLike: TransactionLike

      Returns Promise<CoinInfo>

    • Convenience wrapper around getInputsInfo that returns only the balance.

      Parameters

      • txLike: TransactionLike

      Returns Promise<bigint>

    • Returns aggregated Coin info (balance, capacity, count) for all Coin outputs in the transaction.

      Parameters

      • txLike: TransactionLike

      Returns Promise<CoinInfo>

    • Convenience wrapper around getOutputsInfo that returns only the balance.

      Parameters

      • txLike: TransactionLike

      Returns Promise<bigint>

    • Returns inputs minus outputs as a CoinInfo. Positive balance means tokens are burned; positive capacity means Coins provide surplus CKB.

      Parameters

      • txLike: TransactionLike

      Returns Promise<CoinInfo>

    • Convenience wrapper around getInfoBurned that returns only the balance (inputs − outputs).

      Parameters

      • txLike: TransactionLike

      Returns Promise<bigint>

    • Low-level input selector driven by a custom accumulator. For each candidate Coin cell the accumulator receives (state, cell, coinInfo) and returns the next state to keep going, or undefined to stop.

      Type Parameters

      • T

      Parameters

      • txLike: TransactionLike
      • from: Signer
      • accumulator: (
            acc: T,
            cell: Cell,
            coinInfo: CoinInfo,
        ) => T | Promise<T | undefined> | undefined
      • init: T

      Returns Promise<{ tx: Transaction; addedCount: number; accumulated?: T }>

      accumulated is undefined if the target was reached before all cells were visited.

      Does not add cellDeps. Use complete / completeChangeToLock / completeBy instead.

      // Collect inputs until balance reaches a target
      const { tx } = await coin.completeInputs(
      tx, signer,
      (acc, _cell, coinInfo) => {
      const next = acc + coinInfo.balance;
      return next >= target ? undefined : next;
      },
      ccc.Zero,
      );
    • Adds Coin inputs until both the Coin balance gap and the CKB capacity gap are covered.

      Parameters

      • txLike: TransactionLike
      • from: Signer
      • OptionalbalanceTweak: NumLike | null

        Extra Coin balance to require beyond what outputs consume.

      • OptionalcapacityTweak: NumLike | null

        Extra CKB capacity to require beyond what outputs consume.

      Returns Promise<{ addedCount: number; tx: Transaction }>

      if the signer has insufficient Coin balance.

      Does not add cellDeps. Use complete / completeChangeToLock / completeBy instead.

      const { tx: completedTx } = await coin.completeInputsByBalance(tx, signer);
      
    • Adds ALL available Coins from the signer as inputs. Useful for consolidation or full sweeps.

      Parameters

      • txLike: TransactionLike
      • from: Signer

      Returns Promise<{ addedCount: number; tx: Transaction }>

      Does not add cellDeps. Use complete / completeChangeToLock / completeBy instead.

    • Low-level completion primitive. Adds Coin inputs, then calls change(tx, balance) to write the change output. change is called twice: once on a clone to measure the extra capacity the change cell needs, and once on the real transaction with the final balance.

      Parameters

      • txLike: TransactionLike
      • signer: Signer
      • change: (tx: Transaction, balance: bigint) => void | Promise<void>

        Callback that receives the transaction and the excess Coin balance, and should write the change output in place. Must be side-effect-free beyond modifying tx.

      • Optionaloptions: { shouldAddInputs?: boolean | null }
        • OptionalshouldAddInputs?: boolean | null

          When false, skips input sourcing entirely and calls change once with the current balance. Defaults to true.

      Returns Promise<CoinCompleteResponse>

      const { tx: completedTx } = await coin.complete(tx, signer, (tx, balance) => {
      tx.addOutput({ lock: changeLock, type: coin.script }, ccc.numLeToBytes(balance, 16));
      });
    • Completes the transaction by writing the excess Coin balance into the existing output at index. The output must already be a valid Coin cell with this type script.

      Parameters

      • txLike: TransactionLike
      • signer: Signer
      • indexLike: NumLike
      • Optionaloptions: {
            shouldAddInputs?: boolean | null;
            transformer?:
                | ((cell: CellAny) => CellAnyLike | Promise<CellAnyLike>)
                | null;
        }
        • OptionalshouldAddInputs?: boolean | null
        • Optionaltransformer?: ((cell: CellAny) => CellAnyLike | Promise<CellAnyLike>) | null

          Optional callback to further modify the change cell after the balance has been written into outputData[0..16). Receives the updated cell and returns the final cell. Any capacity below the data minimum is raised automatically; capacity above the minimum is preserved as-is. The transformer runs on every change call, so it must be idempotent with respect to data layout.

      Returns Promise<
          {
              tx: Transaction;
              addedInputs: number;
              hasChanged: boolean;
              changeIndex: number
              | undefined;
          },
      >

      If the output at index does not exist or is not a valid Coin.

      // Change goes into output 1 of the transaction
      const completedTx = await coin.completeChangeToOutput(tx, signer, 1);
    • Completes the transaction by creating a new change output locked to changeLike.

      Parameters

      • txLike: TransactionLike
      • signer: Signer
      • changeLike: ScriptLike
      • Optionaloptions: {
            shouldAddInputs?: boolean | null;
            transformer?:
                | ((cell: CellAny) => CellAnyLike | Promise<CellAnyLike>)
                | null;
        }
        • OptionalshouldAddInputs?: boolean | null
        • Optionaltransformer?: ((cell: CellAny) => CellAnyLike | Promise<CellAnyLike>) | null

          Optional callback to further modify the change cell after the balance has been encoded into outputData[0..16). Use this to append protocol-specific data or reserve extra capacity.

      Returns Promise<CoinCompleteResponse>

      const { script: changeLock } = await signer.getRecommendedAddressObj();
      const { tx: completedTx, changeIndex } = await coin.completeChangeToLock(tx, signer, changeLock);
      // Append extra protocol data after the 16-byte balance prefix
      const { tx: completedTx } = await coin.completeChangeToLock(tx, signer, changeLock, {
      transformer: async (cell) => ({
      ...cell,
      outputData: ccc.hexFrom(ccc.bytesConcat(ccc.bytesFrom(cell.outputData), extraData)),
      }),
      });
    • Convenience wrapper around completeChangeToLock using the signer's recommended address.

      Parameters

      • tx: TransactionLike
      • from: Signer
      • Optionaloptions: {
            shouldAddInputs?: boolean | null;
            transformer?:
                | ((cell: CellAny) => CellAnyLike | Promise<CellAnyLike>)
                | null;
        }

      Returns Promise<CoinCompleteResponse>

      const { tx: completedTx } = await coin.completeBy(tx, signer);
      await completedTx.completeInputsByCapacity(signer);
      await completedTx.completeFeeBy(signer);
      await signer.sendTransaction(completedTx);

      completeChangeToLock for more control over the change destination.