Constructs a new UDT (User Defined Token) script instance. By default it is a SSRI-compliant UDT. This class supports both SSRI-compliant UDTs and legacy sUDT/xUDT standard tokens.
The script code cell outpoint of the UDT. This points to the cell containing the UDT script code
The type script of the UDT that uniquely identifies this token
Optionalconfig: null | UdtConfigLikeOptional configuration object for advanced settings
Configuration object type for UDT instances. This type defines the optional configuration parameters that can be passed when creating a UDT instance to customize its behavior.
Optionalexecutor?: Executor | nullOptional SSRI executor instance for advanced UDT operations. When provided, enables SSRI-compliant features like metadata queries and advanced transfer operations.
Optionalfilter?: ClientIndexerSearchKeyFilterLike | nullOptional custom search filter for finding UDT cells. If not provided, a default filter will be created that matches cells with the UDT's type script and valid output data length.
// Basic UDT instance
const udt = new Udt(
{ txHash: "0x...", index: 0 }, // code outpoint
{ codeHash: "0x...", hashType: "type", args: "0x..." } // type script
);
// UDT with SSRI executor for advanced features
const ssriUdt = new Udt(
codeOutPoint,
typeScript,
{ executor: ssriExecutor }
);
// UDT with custom filter (advanced usage)
const customUdt = new Udt(
codeOutPoint,
typeScript,
{
filter: {
script: typeScript,
outputDataLenRange: [16, 32], // Only cells with 16-32 bytes output data
}
}
);
Default Filter Behavior: If no custom filter is provided, a default filter is created with:
script: Set to the provided UDT type scriptoutputDataLenRange: [16, "0xffffffff"] to match valid UDT cellsSSRI Compliance: When an executor is provided, the UDT instance can use SSRI-compliant features like:
Legacy Support: Even without an executor, the UDT class supports basic operations for legacy sUDT/xUDT tokens.
ReadonlyscriptThe type script that uniquely identifies this UDT token. This script is used to distinguish UDT cells from other cell types and to identify which cells belong to this specific UDT token.
ReadonlyfilterThe search filter used to find UDT cells controlled by signers. This filter is automatically configured to match cells with this UDT's type script and appropriate output data length (minimum 16 bytes for UDT balance storage).
The filter includes:
script: Set to this UDT's type scriptoutputDataLenRange: [16, "0xffffffff"] to ensure valid UDT cellsThis filter is used internally by methods like:
calculateInfo() and calculateBalance() for scanning all UDT cellscompleteInputs() and related methods for finding suitable input cellsconst udt = new Udt(codeOutPoint, scriptConfig);
// The filter is used internally, but you can access it if needed
console.log(`Filter script: ${udt.filter.script?.hash()}`);
console.log(`Output data range: ${udt.filter.outputDataLenRange}`);
// Manually find cells using the same filter
for await (const cell of signer.findCells(udt.filter)) {
console.log(`Found UDT cell with balance: ${udt.balanceFrom(signer.client, cell)}`);
}
Retrieves the human-readable name of the User Defined Token. This method queries the UDT script to get the token's display name, which is typically used in user interfaces and wallets.
Optionalcontext: ContextScriptOptional script execution context for additional parameters
A promise resolving to an ExecutorResponse containing the token's name, or undefined if the name is not available or the script doesn't support this method
Retrieves the symbol (ticker) of the User Defined Token. The symbol is typically a short abbreviation used to identify the token, similar to stock ticker symbols (e.g., "BTC", "ETH", "USDT").
Optionalcontext: ContextScriptOptional script execution context for additional parameters
A promise resolving to an ExecutorResponse containing the token's symbol, or undefined if the symbol is not available or the script doesn't support this method
Retrieves the number of decimal places for the User Defined Token. This value determines how the token amount should be displayed and interpreted. For example, if decimals is 8, then a balance of 100000000 represents 1.0 tokens.
Optionalcontext: ContextScriptOptional script execution context for additional parameters
A promise resolving to an ExecutorResponse containing the number of decimals, or undefined if decimals are not specified or the script doesn't support this method
const udt = new Udt(codeOutPoint, scriptConfig);
const decimalsResponse = await udt.decimals();
if (decimalsResponse.res !== undefined) {
console.log(`Token decimals: ${decimalsResponse.res}`);
// Convert raw amount to human-readable format
const humanReadable = rawAmount / (10 ** Number(decimalsResponse.res));
}
Retrieves the icon URL or data URI for the User Defined Token. This can be used to display a visual representation of the token in user interfaces. The returned value may be a URL pointing to an image file or a data URI containing the image data directly.
Optionalcontext: ContextScriptOptional script execution context for additional parameters
A promise resolving to an ExecutorResponse containing the icon URL/data, or undefined if no icon is available or the script doesn't support this method
StaticbalanceInternalExtracts the UDT balance from raw output data without validation.
⚠️ Warning: This is an unsafe method. The caller must ensure that the
provided outputData is from a valid UDT cell. This method does not
verify the cell's type script or data length, and it assumes the data is
at least 16 bytes long. For safe balance extraction from a cell, use
balanceFrom.
The raw output data of a cell, as a hex string or byte array.
The UDT balance as a ccc.Num. Returns 0 if the data is empty.
Extracts UDT information (balance, capacity, count) from a list of cells.
This method iterates through the provided cells, filters for valid UDT cells belonging to this token, and aggregates their information.
The client instance, which may be used by subclasses for network requests.
A list or a nested list of cells to process.
Optionalacc: UdtInfoLikeAn optional UdtInfoLike object to accumulate results into.
A promise resolving to a UdtInfo object with the total balance, capacity,
and count of valid UDT cells found in the list.
The base implementation of this method operates locally on the provided cell data and does not perform any network requests. However, subclasses may override this method to introduce network requests for more complex logic.
const udt = new Udt(codeOutPoint, scriptConfig);
const cells = [cell1, cell2, nonUdtCell];
const { balance, capacity, count } = await udt.infoFrom(client, cells);
console.log(`Total UDT balance: ${balance}`);
console.log(`Total capacity of UDT cells: ${capacity}`);
console.log(`Number of UDT cells: ${count}`);
Calculates the total UDT balance from a list of cells.
This is a convenience method that wraps infoFrom and returns only the balance.
The client instance.
A list or a nested list of cells to process.
Optionalacc: null | NumLikeAn optional initial balance to accumulate on.
A promise resolving to the total UDT balance from the provided cells.
Calculates comprehensive information about all UDT cells controlled by the signer. This method scans through every UDT cell that the signer controls and aggregates their balance, capacity, and count information.
⚠️ Performance Warning: This is an expensive operation that scales with the number of UDT cells. For addresses with many UDT cells (hundreds or thousands), this method can take significant time and resources. Use sparingly and consider caching results.
The signer whose UDT cells to scan and analyze
Optionaloptions: { source?: null | "chain" | "local" }Optional configuration for the calculation
Optionalsource?: null | "chain" | "local"Data source to use: "chain" (default) for on-chain data, "local" for local indexer cache
A promise resolving to a UdtInfo object containing the aggregated balance, capacity, and count.
const udt = new Udt(codeOutPoint, scriptConfig);
// Calculate comprehensive UDT information from chain (default)
const info = await udt.calculateInfo(signer);
console.log(`Total UDT balance: ${info.balance}`);
console.log(`Total capacity used: ${info.capacity} CKB`);
console.log(`Number of UDT cells: ${info.count}`);
// Use local cache for faster response (may be less up-to-date)
const localInfo = await udt.calculateInfo(signer, { source: "local" });
console.log(`Local cached balance: ${localInfo.balance}`);
// Use for wallet balance display
const balanceInTokens = ccc.fixedPointToString(info.balance, 8); // Assuming 8 decimals
console.log(`Balance: ${balanceInTokens} tokens in ${info.count} cells`);
Performance Considerations:
getInputsInfo() or getOutputsInfo() insteadData Source Options:
"chain" (default): Queries the blockchain directly for the most up-to-date information"local": Uses local indexer cache, faster but potentially stale dataUse Cases:
Alternative Methods:
calculateBalance() if you only need the total balancecompleteInputsAll() if you need to collect all cells for a transactionCalculates the total UDT balance across all cells controlled by the signer. This method provides a convenient way to get the complete UDT balance without needing the additional capacity and count information.
⚠️ Performance Warning: This is an expensive operation that scans all UDT cells. For addresses with many UDT cells, this method can be slow and resource-intensive. Consider caching results and using sparingly in production applications.
The signer whose total UDT balance to calculate
Optionaloptions: { source?: null | "chain" | "local" }Optional configuration for the calculation
Optionalsource?: null | "chain" | "local"Data source to use: "chain" (default) for on-chain data, "local" for local indexer cache
A promise resolving to the total UDT balance across all cells
const udt = new Udt(codeOutPoint, scriptConfig);
// Get total balance for wallet display (from chain)
const totalBalance = await udt.calculateBalance(signer);
console.log(`Total UDT balance: ${totalBalance}`);
// Get balance from local cache for faster response
const cachedBalance = await udt.calculateBalance(signer, { source: "local" });
console.log(`Cached UDT balance: ${cachedBalance}`);
// Convert to human-readable format (assuming 8 decimals)
const decimals = await udt.decimals();
if (decimals.res !== undefined) {
const humanReadable = ccc.fixedPointToString(totalBalance, Number(decimals.res));
console.log(`Balance: ${humanReadable} tokens`);
}
// Check if user has sufficient balance for a transfer
const requiredAmount = ccc.fixedPointFrom(100);
if (totalBalance >= requiredAmount) {
console.log("Sufficient balance for transfer");
} else {
console.log(`Insufficient balance. Need ${requiredAmount - totalBalance} more`);
}
Performance Considerations:
calculateInfo() and extracts only the balanceData Source Options:
"chain" (default): Queries the blockchain directly for the most up-to-date balance"local": Uses local indexer cache, faster but potentially stale dataWhen to Use:
When NOT to Use:
calculateInfo() instead)Alternative Methods:
calculateInfo() if you need additional information beyond balancegetInputsBalance() for transaction input analysisgetOutputsBalance() for transaction output analysisAdds the UDT script code as a cell dependency to the transaction. This method ensures that the transaction includes the necessary cell dependency for the UDT script code, which is required for any transaction that uses this UDT.
The transaction to add the cell dependency to
A new transaction with the UDT code cell dependency added
const udt = new Udt(codeOutPoint, scriptConfig);
// Create a basic transaction
let tx = ccc.Transaction.from({
outputs: [{ lock: recipientLock, type: udt.script }],
outputsData: [ccc.numLeToBytes(100, 16)]
});
// Add UDT code dependency
tx = udt.addCellDeps(tx);
// Now the transaction can be completed and sent
await tx.completeInputsByCapacity(signer);
await tx.completeFeeBy(signer);
When to Use:
transfer() and mint()Cell Dependency Details:
Note: Most high-level UDT methods automatically add this dependency, so manual usage is typically only needed for custom transaction construction.
Transfers UDT to specified addresses. This method creates a transaction that transfers UDT tokens to one or more recipients. It can build upon an existing transaction to achieve combined actions.
The signer that will authorize and potentially pay for the transaction
Array of transfer operations to perform
Optionaltx: null | TransactionLikeOptional existing transaction to build upon. If not provided, a new transaction will be created
A promise resolving to an ExecutorResponse containing the transaction with transfer operations
Mutation - This method represents a mutation of the onchain state and will return a transaction object.
const { script: change } = await signer.getRecommendedAddressObj();
const { script: to } = await ccc.Address.fromString(receiver, signer.client);
const udt = new Udt(
{
txHash: "0x4e2e832e0b1e7b5994681b621b00c1e65f577ee4b440ef95fa07db9bb3d50269",
index: 0,
},
{
codeHash: "0xcc9dc33ef234e14bc788c43a4848556a5fb16401a04662fc55db9bb201987037",
hashType: "type",
args: "0x71fd1985b2971a9903e4d8ed0d59e6710166985217ca0681437883837b86162f"
},
);
const { res: tx } = await udt.transfer(
signer,
[{ to, amount: 100 }],
);
const completedTx = await udt.completeBy(tx, signer);
await completedTx.completeInputsByCapacity(signer);
await completedTx.completeFeeBy(signer);
const transferTxHash = await signer.sendTransaction(completedTx);
Mints new tokens to specified addresses. This method creates new UDT tokens and assigns them to the specified recipients. The minting operation requires appropriate permissions and may be restricted based on the UDT's implementation.
The signer that will authorize and potentially pay for the transaction
Array of mint operations to perform
Optionaltx: null | TransactionLikeOptional existing transaction to build upon. If not provided, a new transaction will be created
A promise resolving to an ExecutorResponse containing the transaction with mint operations
const udt = new Udt(codeOutPoint, scriptConfig);
const { script: recipientLock } = await ccc.Address.fromString(recipientAddress, signer.client);
const mintResponse = await udt.mint(
signer,
[
{ to: recipientLock, amount: ccc.fixedPointFrom(1000) }, // Mint 1000 tokens
{ to: anotherLock, amount: ccc.fixedPointFrom(500) } // Mint 500 tokens
]
);
// Complete the transaction
const tx = mintResponse.res;
await tx.completeInputsByCapacity(signer);
await tx.completeFeeBy(signer, changeLock);
const txHash = await signer.sendTransaction(tx);
Checks if a cell is a valid UDT cell for this token. A valid UDT cell must have this UDT's type script and contain at least 16 bytes of output data (the minimum required for storing the UDT balance as a 128-bit little-endian integer).
The cell to check, which can be a ccc.Cell or a ccc.CellLike object.
True if the cell is a valid UDT cell for this token, false otherwise
Retrieves comprehensive information about UDT inputs in a transaction. This method analyzes all input cells and returns detailed statistics including total UDT balance, total capacity occupied, and the number of UDT cells.
The client to fetch input cell data
The transaction to analyze
A promise resolving to an object containing: - balance: Total UDT balance from all input cells - capacity: Total capacity occupied by all UDT input cells - count: Number of UDT input cells
const udt = new Udt(codeOutPoint, scriptConfig);
const tx = ccc.Transaction.from(existingTransaction);
const inputsInfo = await udt.getInputsInfo(client, tx);
console.log(`UDT inputs: ${inputsInfo.count} cells`);
console.log(`Total UDT balance: ${inputsInfo.balance}`);
console.log(`Total capacity: ${inputsInfo.capacity}`);
Calculates the total UDT balance from all inputs in a transaction. This method examines each input cell and sums up the UDT amounts for cells that have this UDT's type script.
The client to fetch input cell data
The transaction to analyze
A promise resolving to the total UDT balance from all inputs
Retrieves comprehensive information about UDT outputs in a transaction. This method analyzes all output cells and returns detailed statistics including total UDT balance, total capacity occupied, and the number of UDT cells.
The client parameter (unused for outputs since data is already available)
The transaction to analyze
A promise resolving to an object containing: - balance: Total UDT balance from all output cells - capacity: Total capacity occupied by all UDT output cells - count: Number of UDT output cells
const udt = new Udt(codeOutPoint, scriptConfig);
const tx = ccc.Transaction.from({
outputs: [
{ lock: recipientLock, type: udt.script },
{ lock: changeLock, type: udt.script }
],
outputsData: [
ccc.numLeToBytes(1000, 16), // 1000 UDT to recipient
ccc.numLeToBytes(500, 16) // 500 UDT as change
]
});
const outputsInfo = await udt.getOutputsInfo(client, tx);
console.log(`UDT outputs: ${outputsInfo.count} cells`);
console.log(`Total UDT balance: ${outputsInfo.balance}`); // 1500
console.log(`Total capacity: ${outputsInfo.capacity}`);
This method provides more comprehensive information than getOutputsBalance,
making it useful for transaction validation, analysis, and UI display.
Only cells with this UDT's type script are included in the statistics.
This is an async method for consistency with getInputsInfo, though it doesn't
actually need to fetch data since output information is already available.
Calculates the total UDT balance from all outputs in a transaction. This method examines each output cell and sums up the UDT amounts for cells that have this UDT's type script.
The client parameter (passed to getOutputsInfo for consistency)
The transaction to analyze
A promise resolving to the total UDT balance from all outputs
const udt = new Udt(codeOutPoint, scriptConfig);
const tx = ccc.Transaction.from({
outputs: [
{ lock: recipientLock, type: udt.script },
{ lock: changeLock, type: udt.script }
],
outputsData: [
ccc.numLeToBytes(1000, 16), // 1000 UDT to recipient
ccc.numLeToBytes(500, 16) // 500 UDT as change
]
});
const outputBalance = await udt.getOutputsBalance(client, tx);
console.log(`Total UDT output balance: ${outputBalance}`); // 1500
Calculates the net UDT balance that would be burned (destroyed) in a transaction. This is the difference between the total UDT balance in inputs and outputs. A positive value indicates UDT tokens are being burned, while a negative value indicates more UDT is being created than consumed (which may require minting permissions).
The client to fetch input cell data
The transaction to analyze
A promise resolving to the net UDT balance burned (inputs - outputs)
const udt = new Udt(codeOutPoint, scriptConfig);
const tx = ccc.Transaction.from(existingTransaction);
const burned = await udt.getBalanceBurned(client, tx);
if (burned > 0) {
console.log(`${burned} UDT tokens will be burned`);
} else if (burned < 0) {
console.log(`${-burned} UDT tokens will be created`);
} else {
console.log('UDT balance is conserved');
}
Low-level method to complete UDT inputs for a transaction using a custom accumulator function. This method provides maximum flexibility for input selection by allowing custom logic through the accumulator function. It's primarily used internally by other completion methods.
The type of the accumulator value
The transaction to complete with UDT inputs
The signer that will provide UDT inputs
Function that determines when to stop adding inputs based on accumulated state
Initial value for the accumulator
A promise resolving to an object containing: - tx: The transaction with added inputs - addedCount: Number of inputs that were added - accumulated: Final accumulator value (undefined if target was reached)
const udt = new Udt(codeOutPoint, scriptConfig);
// Custom accumulator to track both balance and capacity
const result = await udt.completeInputs(
tx,
signer,
([balanceAcc, capacityAcc], cell) => {
const balance = Udt.balanceFromUnsafe(cell.outputData);
const newBalance = balanceAcc + balance;
const newCapacity = capacityAcc + cell.cellOutput.capacity;
// Stop when we have enough balance and capacity
return newBalance >= requiredBalance && newCapacity >= requiredCapacity
? undefined // Stop adding inputs
: [newBalance, newCapacity]; // Continue with updated accumulator
},
[ccc.Zero, ccc.Zero] // Initial [balance, capacity]
);
Completes UDT inputs for a transaction to satisfy both UDT balance and capacity requirements. This method implements intelligent input selection that considers both UDT token balance and cell capacity constraints, optimizing for minimal cell usage while meeting all requirements. It uses sophisticated balance calculations and early exit optimizations for efficiency.
The transaction to complete with UDT inputs
The signer that will provide UDT inputs
OptionalbalanceTweak: NumLikeOptional additional UDT balance requirement beyond outputs (default: 0)
OptionalcapacityTweak: NumLikeOptional additional CKB capacity requirement beyond outputs (default: 0)
A promise resolving to an object containing: - tx: The modified transaction with added UDT inputs - addedCount: Number of UDT input cells that were added
const udt = new Udt(codeOutPoint, scriptConfig);
// Basic usage: add inputs to cover UDT outputs
const tx = ccc.Transaction.from({
outputs: [{ lock: recipientLock, type: udt.script }],
outputsData: [ccc.numLeToBytes(1000, 16)]
});
const { tx: completedTx, addedCount } = await udt.completeInputsByBalance(tx, signer);
console.log(`Added ${addedCount} UDT inputs to cover 1000 UDT requirement`);
// Advanced usage: with balance and capacity tweaks
const { tx: advancedTx, addedCount: advancedCount } = await udt.completeInputsByBalance(
tx,
signer,
ccc.numFrom(100), // Extra 100 UDT balance needed
ccc.fixedPointFrom(5000) // Extra 5000 capacity needed
);
This method implements sophisticated dual-constraint input selection with the following logic:
Constraint Calculations:
(input UDT balance) - (output UDT balance) - balanceTweakmin((input UDT capacity) - (output UDT capacity), total_tx_fee) - capacityTweak
The capacity calculation determines how much capacity from UDT cells is available to cover CKB requirements (like transaction fees).
It's capped by the total transaction fee to avoid over-providing capacity from UDT cells if not needed.Early Exit Optimization:
addedCount: 0 if both balance and capacity constraints are satisfiedSmart Input Selection:
balanceAcc >= 0 && capacityAcc >= 0Error Handling:
ErrorUdtInsufficientCoin with exact shortfall amount if insufficient UDT balanceAdds ALL available UDT cells from the signer as inputs to the transaction.
Unlike completeInputsByBalance which adds only the minimum required inputs,
this method collects every available UDT cell that the signer controls,
regardless of the transaction's actual UDT requirements.
The transaction to add UDT inputs to
The signer that will provide all available UDT inputs
A promise resolving to an object containing: - tx: The transaction with all available UDT inputs added - addedCount: Number of UDT input cells that were added
const udt = new Udt(codeOutPoint, scriptConfig);
// Create a transaction (can be empty or have existing outputs)
const tx = ccc.Transaction.from({
outputs: [{ lock: recipientLock, type: udt.script }],
outputsData: [ccc.numLeToBytes(100, 16)] // Send 100 UDT
});
// Add ALL available UDT cells as inputs
const { tx: completedTx, addedCount } = await udt.completeInputsAll(tx, signer);
console.log(`Added ${addedCount} UDT cells as inputs`);
// The transaction now contains all UDT cells the signer controls
const totalInputBalance = await udt.getInputsBalance(completedTx, client);
console.log(`Total UDT input balance: ${totalInputBalance}`);
Use Cases:
Important Considerations:
completeInputsByBalance instead if you only need specific amountsBehavior:
Completes a UDT transaction by adding inputs and handling change with a custom change function. This is a low-level method that provides maximum flexibility for handling UDT transaction completion. The change function is called to handle excess UDT balance and can return the capacity cost of the change.
The transaction to complete
The signer that will provide UDT inputs
Function to handle excess UDT balance. Called with (tx, balance, shouldModify) where shouldModify indicates if the function should actually modify the transaction
Optionaloptions: { shouldAddInputs?: boolean }Optional configuration
OptionalshouldAddInputs?: booleanWhether to automatically add inputs. Defaults to true
A promise resolving to the completed transaction
const udt = new Udt(codeOutPoint, scriptConfig);
const completedTx = await udt.complete(
tx,
signer,
(tx, balance, shouldModify) => {
if (shouldModify && balance > 0) {
// Add change output
const changeData = ccc.numLeToBytes(balance, 16);
tx.addOutput({ lock: changeLock, type: udt.script }, changeData);
return ccc.CellOutput.from({ lock: changeLock, type: udt.script }, changeData).capacity;
}
return 0;
}
);
Completes a UDT transaction by adding change to an existing output at the specified index. This method modifies an existing UDT output in the transaction to include any excess UDT balance as change, rather than creating a new change output.
The transaction to complete
The signer that will provide UDT inputs
The index of the output to modify with change balance
Optionaloptions: { shouldAddInputs?: boolean }Optional configuration
OptionalshouldAddInputs?: booleanWhether to automatically add inputs. Defaults to true
A promise resolving to the completed transaction
const udt = new Udt(codeOutPoint, scriptConfig);
// Create transaction with a UDT output that will receive change
const tx = ccc.Transaction.from({
outputs: [
{ lock: recipientLock, type: udt.script },
{ lock: changeLock, type: udt.script } // This will receive change
],
outputsData: [
ccc.numLeToBytes(1000, 16), // Send 1000 UDT
ccc.numLeToBytes(0, 16) // Change output starts with 0
]
});
// Complete with change going to output index 1
const completedTx = await udt.completeChangeToOutput(tx, signer, 1);
// Output 1 now contains the excess UDT balance
Completes a UDT transaction by adding necessary inputs and handling change. This method automatically adds UDT inputs to cover the required output amounts and creates a change output if there's excess UDT balance.
The transaction to complete, containing UDT outputs
The signer that will provide UDT inputs
The lock script where any excess UDT balance should be sent as change
Optionaloptions: { shouldAddInputs?: boolean }Optional configuration for the completion process
OptionalshouldAddInputs?: booleanWhether to automatically add inputs. Defaults to true
A promise resolving to the completed transaction with inputs and change output added
const udt = new Udt(codeOutPoint, scriptConfig);
// Create a transaction with UDT outputs
const tx = ccc.Transaction.from({
outputs: [
{ lock: recipientLock, type: udt.script }
],
outputsData: [ccc.numLeToBytes(1000, 16)] // Send 1000 UDT
});
// Complete with change going to sender's address
const { script: changeLock } = await signer.getRecommendedAddressObj();
const completedTx = await udt.completeChangeToLock(tx, signer, changeLock);
// The transaction now has:
// - Sufficient UDT inputs to cover the 1000 UDT output
// - A change output if there was excess UDT balance
Completes a UDT transaction using the signer's recommended address for change. This is a convenience method that automatically uses the signer's recommended address as the change destination, making it easier to complete UDT transactions without manually specifying a change address.
The transaction to complete, containing UDT outputs
The signer that will provide UDT inputs and receive change
Optionaloptions: { shouldAddInputs?: boolean }Optional configuration for the completion process
OptionalshouldAddInputs?: booleanWhether to automatically add inputs. Defaults to true
A promise resolving to the completed transaction with inputs and change output added
const udt = new Udt(codeOutPoint, scriptConfig);
// Create a transfer transaction
const transferResponse = await udt.transfer(
signer,
[{ to: recipientLock, amount: 1000 }]
);
// Complete the transaction (change will go to signer's address)
const completedTx = await udt.completeBy(transferResponse.res, signer);
// Add capacity inputs and fee
await completedTx.completeInputsByCapacity(signer);
await completedTx.completeFeeBy(signer, changeLock);
const txHash = await signer.sendTransaction(completedTx);
completeChangeToLock for more control over the change destination
Represents a User Defined Token (UDT) script compliant with the SSRI protocol.
This class provides a comprehensive implementation for interacting with User Defined Tokens, supporting various token operations such as querying metadata, checking balances, and performing transfers. It supports both SSRI-compliant UDTs and legacy sUDT/xUDT standard tokens.