True if all tokens are configured
Checks token allowances for all deposits against the orderbook contract.
Queries the blockchain to determine current allowances for each output token that will be deposited. This helps determine which tokens need approval before the order can be created.
const result = await gui.checkAllowances(walletAddress);
if (result.error) {
console.error("Allowance check failed:", result.error.readableMsg);
return;
}
const [allowance1, allowance2, ...] = result.value;
const {
// token is the token address
token,
// allowance is the current allowance for the token
allowance,
} = allowance1;
Wallet address to check allowances for
Current allowances for all deposit tokens
Validates that all required tokens have been selected.
Checks if all tokens in the select-tokens configuration have been given addresses. Use this before generating transactions to ensure completeness.
const result = gui.checkSelectTokens();
if (result.error) {
console.error("Selection incomplete:", result.error.readableMsg);
return;
// Do something
All required tokens are configured
Manually triggers the state update callback.
Calls the registered state update callback with the current serialized state. This is typically called automatically after state-changing operations, but can be triggered manually if needed.
// Manual state update trigger
const result = gui.executeStateUpdateCallback();
if (result.error) {
console.error("Callback error:", result.error.readableMsg);
}
Callback executed successfully or no callback registered
Generates calldata for adding the order to the orderbook.
Creates the addOrder calldata with all field values applied to the Rainlang code and proper vault configurations.
const result = await gui.generateAddOrderCalldata();
if (result.error) {
console.error("Cannot create order:", result.error.readableMsg);
// Show user what needs to be fixed
return;
}
const addOrderCalldata = result.value;
// Do something with the add order calldata
Encoded addOrder call ready for execution
Generates approval calldatas for tokens that need increased allowances.
Automatically checks current allowances and generates approval calldata whenever the on-chain allowance differs from the planned deposit amount.
const result = await gui.generateApprovalCalldatas(walletAddress);
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
// If there are approvals
const [approval1, approval2, ...] = result.value;
const {
// token is the token address
token,
// calldata is the approval calldata
calldata,
} = approval1;
Wallet address that will approve the tokens
Approval calldatas needed for insufficient allowances
Generates a multicall combining all deposits and add order in one calldata.
This is the most efficient way to deploy an order, combining all necessary operations into a single calldata to minimize gas costs and ensure atomicity.
The multicall includes:
const result = await gui.generateDepositAndAddOrderCalldatas();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const multicallData = result.value;
// Do something with the multicall data
Multicall calldata combining deposits and addOrder
Generates calldata for depositing tokens into orderbook vaults.
Creates deposit calldatas for all configured deposits, automatically skipping zero amounts and ensuring vault IDs are properly assigned.
const result = await gui.generateDepositCalldatas();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
// If there are deposits
const [depositCalldata1, depositCalldata2, ...] = result.value;
const {
// calldata is the deposit calldata
calldata,
} = depositCalldata1;
Deposit calldatas to execute or NoDeposits if none configured
Exports the current configuration as a complete dotrain text file.
This generates a valid dotrain file with YAML frontmatter and Rainlang code, preserving all configurations and bindings. Useful for saving or sharing orders.
The output follows the standard dotrain format:
gui:
...
---
#binding1 !The binding value
#calculate-io
...
const result = gui.generateDotrainText();
if (result.error) {
console.error("Export failed:", result.error.readableMsg);
return;
}
const dotrain = result.value;
// Do something with the dotrain
Complete dotrain content with YAML frontmatter separator
Gets the balance of a specific token for a given owner address
Retrieves the ERC20 token balance by connecting to the current deployment's network RPC and querying the token contract.
const result = await gui.getAccountBalance("0x123...", "0xabc...");
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
console.log("Raw balance:", result.value.balance);
console.log("Formatted balance:", result.value.formattedBalance);
Token contract address
Owner address to check balance for
Owner balance in both raw and human-readable format
Gets all field definitions with optional filtering by default value presence.
This method helps build dynamic forms by providing all field configurations at once. The filter option allows separating required fields (no default) from optional fields (with default).
// Get all fields
const allFieldsResult = gui.getAllFieldDefinitions();
if (allFieldsResult.error) {
console.error("Error:", allFieldsResult.error.readableMsg);
return;
}
// Get only required fields (no defaults)
const requiredResult = gui.getAllFieldDefinitions(false);
if (requiredResult.error) {
console.error("Error:", requiredResult.error.readableMsg);
return;
}
const requiredFields = requiredResult.value;
// Get optional fields (with defaults)
const optionalResult = gui.getAllFieldDefinitions(true);
if (optionalResult.error) {
console.error("Error:", optionalResult.error.readableMsg);
return;
}
const optionalFields = optionalResult.value;
Optionalfilter_defaults: null | booleanOptional filter: true for fields with defaults, false for fields without defaults, undefined for all
Filtered field definitions
Gets all configured field values with their metadata.
Returns all field values that have been set, with preset values expanded.
const result = gui.getAllFieldValues();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const [fieldValue1, fieldValue2, ...] = result.value;
const {
// field is the field identifier
field,
// value is the field value
value,
// isPreset is a boolean indicating if the value is a preset
isPreset
} = fieldValue1;
Array of all configured field values
Gets comprehensive configuration for complete UI initialization.
Provides all configuration data needed to build a complete order interface, organized by requirement type for progressive UI construction.
fieldDefinitionsWithoutDefaults - Required fields needing user inputfieldDefinitionsWithDefaults - Optional fields with fallback valuesdeposits - Deposit configurations with tokens and presetsorderInputs - Input token configurationsorderOutputs - Output token configurationsconst result = gui.getAllGuiConfig();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const config = result.value;
// Build required fields section
config.fieldDefinitionsWithoutDefaults.forEach(field => {
// Do something with the fields
});
// Build optional fields section
if (config.fieldDefinitionsWithDefaults.length > 0) {
// Do something with the fields
}
// Build deposits section
config.deposits.forEach(deposit => {
// Do something with the deposits
});
// Show order preview
config.orderInputs.forEach(input => {
// Do something with the order inputs
});
config.orderOutputs.forEach(output => {
// Do something with the order outputs
});
Complete configuration package
Gets information for all tokens used in the current deployment's order.
This function automatically determines which tokens to fetch based on the deployment:
select-tokens is defined, returns info for those tokensThis may trigger multiple blockchain queries if token data isn't cached in YAML. Consider caching the results in your application.
const result = await gui.getAllTokenInfos();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const tokens = result.value;
// Do something with the tokens
Array of complete token information
Gets all tokens configured for the selected deployment's network.
Retrieves token information from the YAML configuration, using cached metadata when available or fetching from blockchain via ERC20 contracts. Results are filtered by the search term (matching name or address) and sorted by address and deduplicated.
// Get all tokens
const result = await gui.getAllTokens();
// Search for specific tokens
const usdcResult = await gui.getAllTokens("USDC");
const addressResult = await gui.getAllTokens("0x1234...");
Optionalsearch: null | stringOptional search term to filter tokens by name, symbol, or address
Array of token information for the current network
Composes the final Rainlang code with all bindings and scenarios applied.
This method updates scenario bindings from current field values and composes the Rainlang code ready to be displayed on the UI.
Updates the internal scenario bindings before composition.
const result = await gui.getComposedRainlang();
if (result.error) {
console.error("Composition error:", result.error.readableMsg);
return;
}
const rainlang = result.value;
// Do something with the rainlang
Composed Rainlang code with comments for each entrypoint
Gets the active deployment's configuration including fields, deposits, and tokens.
This is the primary method for accessing deployment-specific settings that define what inputs are needed from the user. The configuration drives UI generation.
fields - Input fields requiring user configurationdeposits - Token deposits with amounts and presetsselectTokens - Tokens that users must choose addresses fordeployment - Underlying order and scenario configurationconst result = gui.getCurrentDeployment();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const deployment = result.value;
// Do something with the deployment
Active deployment with all configuration details
Gets metadata for the currently active deployment.
Instance method that returns name and description for the deployment selected during initialization.
const result = gui.getCurrentDeploymentDetails();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const details = result.value;
// Do something with the details
Current deployment's metadata
Gets transaction data for order deployment including approvals.
This is the comprehensive function that provides everything needed to deploy an order: approval calldatas, the main deployment transaction, and metadata. Use this for full transaction orchestration.
approvals - Token approval calldatas with symbols for UIdeploymentCalldata - Main order deployment calldataorderbookAddress - Target contract addresschainId - Network identifierconst result = await gui.getDeploymentTransactionArgs(walletAddress);
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const {
// approvals is an array of extended approval calldatas
// extended approval calldata includes the token address, calldata, and symbol
approvals,
// deploymentCalldata is the multicall calldata for the order
deploymentCalldata,
// orderbookAddress is the address of the orderbook
orderbookAddress,
// chainId is the chain ID of the network
chainId,
} = result.value;
Wallet address that will deploy the order
Complete transaction package including approvals and deployment calldata
Gets preset amounts available for a specific deposit token.
Returns the preset values configured for this token in the deployment, useful for building quick-select interfaces.
const result = gui.getDepositPresets("usdc");
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
// items are preset amounts
const [preset1, preset2, ...] = result.value;
Token key from deposits configuration
Array of preset amounts, or empty if no presets
Gets all configured deposit amounts with token information.
Returns deposits as token deposits with human-readable amounts and addresses. This combines the stored deposit amounts with token metadata for display and transaction preparation.
const result = gui.getDeposits();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const [deposit1, deposit2, ...] = result.value;
const {
// token is the token address
token,
// amount is the deposit amount
amount,
// address is the token address
} = deposit1;
Array of deposits with token details and amounts
Gets the complete definition for a specific field including presets and validation.
Use this to build dynamic UIs that adapt to field configurations, showing appropriate input controls, preset options, and validation rules.
const result = gui.getFieldDefinition("max-price");
if (result.error) {
console.error("Not found:", result.error.readableMsg);
return;
}
const {
// field is the field identifier
field,
// name is the display name for the field
name,
// description is the help text for the field
description,
// presets are the available preset options for the field
presets,
// default is the default value for the field if no value is set by the user
default,
// showCustomField is a boolean indicating if the field allows custom input
showCustomField
} = result.value;
Field binding identifier to look up
Complete field configuration
Retrieves a field value with preset expansion and metadata.
This function returns the saved value along with information about whether it's a preset.
const result = gui.getFieldValue("max-price");
if (result.error) {
console.error("Not found:", result.error.readableMsg);
return;
}
const { field, value, isPreset } = result.value;
// field is the field identifier
// value is the field value
// isPreset is a boolean indicating if the value is a preset
Field identifier from the YAML configuration
Field value with the identifier, value, and preset flag
Retrieves the complete GUI configuration including all deployments.
This returns the parsed GUI section from the YAML, filtered to include only the current deployment. Use this to access order-level metadata.
const result = gui.getGuiConfig();
if (result.error) {
console.error("Config error:", result.error.readableMsg);
return;
}
const config = result.value;
// Do something with the config
Complete GUI configuration with name, description, and deployments
Lists tokens that require deposits but haven't been configured.
Returns token keys for deposits that are required by the deployment but haven't been set yet. Use this for validation and user guidance.
const result = gui.getMissingDeposits();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
// items are token keys
const [missing1, missing2, ...] = result.value;
if (missing.length > 0) {
// Do something with the missing tokens
}
Array of token keys needing deposits
Lists field definitions that haven't been configured yet.
Returns field definitions for fields that need values. Use this for validation and to guide users through required configurations.
const result = gui.getMissingFieldValues();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const missing = result.value;
// Do something with the missing
Array of field definitions that need to be set
Gets tokens that need user selection for the current deployment.
Returns tokens defined in the select-tokens section that require user input to specify contract addresses. This enables generic orders that work with user-chosen tokens.
const result = gui.getSelectTokens();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const selectableTokens = result.value;
// Do something with the selectable tokens
Array of selectable token configurations
Retrieves detailed token information from YAML configuration or blockchain.
This function first checks the YAML for cached token data (decimals, name, symbol). If any information is missing, it queries the blockchain to fetch the complete details. This hybrid approach minimizes RPC calls while ensuring accurate data.
The RPC endpoint is determined by the deployment's order network configuration.
// Get token info (may query blockchain)
const result = await gui.getTokenInfo("weth");
if (result.error) {
console.error("Token error:", result.error.readableMsg);
return;
}
const tokenInfo = result.value;
// Do something with the tokenInfo
Token identifier from the YAML tokens section
Complete token details including address, decimals, name, and symbol
Gets all configured vault IDs for inputs and outputs.
Returns a map with 'input' and 'output' keys, where each value is a map of token keys to their configured vault IDs (or undefined if not set).
const result = gui.getVaultIds();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
// Access input token vault IDs
for (const [tokenKey, vaultId] of result.value.get('input')) {
console.log(`Input token ${tokenKey} uses vault ${vaultId || 'none'}`);
}
// Access output token vault IDs
for (const [tokenKey, vaultId] of result.value.get('output')) {
console.log(`Output token ${tokenKey} uses vault ${vaultId || 'none'}`);
}
Map with 'input' and 'output' keys containing token-to-vault-ID maps
Checks if any deposits have been configured.
Quick check to determine if the user has started configuring deposits. Useful for showing different UI states or progress indicators.
const result = gui.hasAnyDeposit();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const hasDeposits = result.value;
if (!hasDeposits) {
// Do something
}
True if at least one deposit exists
Checks if any vault IDs have been configured.
Quick validation to determine if vault configuration has started. Useful for UI state management and validation flows.
const result = gui.hasAnyVaultId();
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const hasVaults = result.value;
// Do something with the has vaults
True if at least one vault ID is set
Checks if a selectable token has been configured with an address.
Use this to determine if a user has provided an address for a select-token, enabling progressive UI updates and validation.
const result = gui.isSelectTokenSet("stable-token");
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const isSelectTokenSet = result.value;
// Do something
Token key from select-tokens configuration
True if token address has been set
Exports the complete GUI state as a compressed, encoded string.
Serializes all current configuration including field values, deposits, selected tokens, and vault IDs into a compact format for persistence or sharing. The output is gzipped and base64-encoded.
const result = gui.serializeState();
if (result.error) {
console.error("Serialization error:", result.error.readableMsg);
return;
}
const state = result.value;
// Do something with the state
Compressed, base64-encoded state data
Sets a deposit amount for a specific token.
Sets the deposit amount for a token, automatically detecting if the amount matches a preset value.
If the amount matches a preset value from the configuration, it's stored as a preset reference for efficiency and consistency.
// Set a custom deposit amount
const result = await gui.setDeposit("usdc", "1000.50");
if (result.error) {
console.error("Deposit error:", result.error.readableMsg);
return;
}
Token key from the deposits configuration
Human-readable amount (e.g., '100.5')
Sets a value for a specific field binding with automatic preset detection.
This function stores the provided value and automatically determines if it matches a preset from the field definition. Preset detection enables the UI to show whether a standard option or custom value is being used.
The function checks if the value matches any preset in the field definition. If it matches, it stores the preset index; otherwise, stores the raw value.
// Set a custom value
const result = gui.setFieldValue("max-price", "1500.50");
if (result.error) {
console.error("Set failed:", result.error.readableMsg);
return;
}
Field identifier from the YAML configuration
Value to save (can be a preset value or custom input)
Batch sets multiple field values in a single operation.
This is more efficient than calling setFieldValue multiple times, especially when loading saved configurations or applying templates. Each value is processed with the same preset detection as individual saves.
const fields = [
{ field: "max-price", value: "1500" },
{ field: "min-amount", value: "100" },
{ field: "slippage", value: "0.5" }
];
const result = gui.setFieldValues(fields);
if (result.error) {
console.error("Batch set failed:", result.error.readableMsg);
return;
}
Array of field-value pairs to save
Sets a custom token address to be used in the order.
Takes a token address provided by the user and queries the blockchain to get the token's name, symbol, and decimals. This information is then cached for efficient access.
The function uses the deployment's network configuration to determine the RPC endpoint for querying token information.
// User selects token
const result = await gui.setSelectToken(
"stable-token",
"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
);
if (result.error) {
console.error("Selection failed:", result.error.readableMsg);
return;
}
// Do something with the token
Token key from select-tokens configuration
Token contract address provided by user
Configures vault IDs for order inputs or outputs.
Sets the vault ID for a specific input or output token. Vault IDs determine which vaults are used for the input or output tokens in the order.
const result1 = gui.setVaultId("input", "token1", "42");
if (result1.error) {
console.error("Error:", result1.error.readableMsg);
return;
}
const result2 = gui.setVaultId("output", "token2", "43");
const result3 = gui.setVaultId("output", "token2", undefined);
Vault type: 'input' or 'output'
Token key to identify which token to set vault for
OptionalvaultId: null | stringVault ID number as string. Omit to clear vault ID
Unsets the deposit amount for a specific token.
Use this to clear a deposit that's no longer needed.
// Unset a specific token deposit
const result = gui.unsetDeposit("usdc");
if (result.error) {
console.error("Unset failed:", result.error.readableMsg);
return;
}
Token key to remove deposit for
Unsets a previously set field value.
Use this to clear a field value, returning it to an unset state.
// Clear a field value
const result = gui.unsetFieldValue("max-price");
if (result.error) {
console.error("Unset failed:", result.error.readableMsg);
return;
}
Field identifier from the YAML configuration
Removes a previously selected token configuration.
Clears the address and cached information for a select-token, returning it to an unselected state.
// Remove token selection
const result = gui.unsetSelectToken("stable-token");
if (result.error) {
console.error("Remove failed:", result.error.readableMsg);
return;
}
Token key to clear
StaticgetGets metadata for a specific deployment by key.
Convenience method that extracts details for a single deployment without parsing all deployments.
const result = await getDeploymentDetail(dotrainYaml, "mainnet-order");
if (result.error) {
console.error("Not found:", result.error.readableMsg);
return;
}
const detail = result.value;
// Do something with the detail
Complete dotrain YAML content
Deployment identifier to look up
Deployment name and description
StaticgetGets metadata for all deployments defined in the configuration.
This static method extracts name and description for each deployment, useful for building deployment selection interfaces with rich descriptions.
const result = await getDeploymentDetails(dotrainYaml);
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
// key is the deployment key
// value is the deployment metadata
for (const [key, value] of result.value) {
const {
// name is the deployment name
// description is the deployment description
name,
description,
// short_description is the deployment short description (optional)
short_description,
} = value;
}
Complete dotrain YAML content
Map of deployment key to metadata
StaticgetLists all available gui deployment keys from a dotrain YAML file.
This function parses the gui section of the YAML frontmatter to extract deployment keys that can be used to initialize a GUI instance. Use this to build deployment selectors in your UI.
const dotrain = `
gui:
deployments:
mainnet-order:
name: "Mainnet Trading"
testnet-order:
name: "Test order"
`;
const result = await DotrainOrderGui.getDeploymentKeys(dotrain);
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const deploymentKeys = result.value;
// Do something with the deploymentKeys
Complete dotrain YAML content including the gui.deployments section
Array of deployment identifiers (keys from the deployments map)
StaticgetExtracts order-level metadata from a dotrain configuration.
This static method allows checking order details without creating a GUI instance, useful for displaying order information before deployment selection.
The YAML must contain:
gui.name - Order display namegui.description - Full order descriptiongui.short-description - Brief summary (optional but recommended)const result = await getOrderDetails(dotrainYaml);
if (result.error) {
console.error("Error:", result.error.readableMsg);
return;
}
const details = result.value;
// Do something with the details
Complete dotrain YAML content
Order name, description, and optional short description
StaticnewRestores a GUI instance from previously serialized state.
Creates a new GUI instance with all configuration restored from a saved state. The dotrain content must match the original for security validation.
The function validates that the dotrain content hasn't changed by comparing hashes. This prevents state injection attacks and ensures consistency.
const result = await DotrainOrderGui.newFromState(dotrainYaml, savedState);
if (result.error) {
console.error("Restore failed:", result.error.readableMsg);
return;
}
const gui = result.value;
// Do something with the gui
Must match the original dotrain content exactly
Previously serialized state string
Optionalstate_update_callback: null | FunctionOptional callback for future state changes
Fully restored GUI instance
StaticnewCreates a new GUI instance for managing a specific deployment configuration.
This is the primary initialization function that sets up the GUI context for a chosen deployment. The instance tracks field values, deposits, token selections, and provides methods for generating order transactions.
The callback function receives a serialized state string on every change, enabling auto-save functionality or state synchronization across components.
// Basic initialization
const result = await DotrainOrderGui.newWithDeployment(dotrainYaml, "mainnet-order");
if (result.error) {
console.error("Init failed:", result.error.readableMsg);
return;
}
const gui = result.value;
// With state persistence
const result = await DotrainOrderGui.newWithDeployment(
dotrainYaml,
"mainnet-order",
(serializedState) => {
localStorage.setItem('orderState', serializedState);
}
);
if (!result.error) {
const gui = result.value;
// Use gui instance...
}
Complete dotrain YAML content with all configurations
Key of the deployment to activate (must exist in YAML)
Optionalstate_update_callback: null | FunctionOptional function called on state changes. After a state change (deposit, field value, vault id, select token, etc.), the callback is called with the new state. This is useful for auto-saving the state of the GUI across sessions.
Initialized GUI instance for further operations
Checks if all required tokens have been selected and configured.
Validates that every token in the select-tokens configuration has been given an address. Use this for overall validation and progress tracking.
Examples