Skip to content

API Documentation

Mojtaba Eshghie edited this page Jul 3, 2024 · 8 revisions

Table of Contents

Library Functions/Classes
Configuration Library readCIConfig, readCIConfigWithPath, readModelFunctionsParams
DCR Information Library getRoles, getActivities, getSimulationXML, getSimulations, getLastSimulationId, getPendingActivities
DCR Execution Library DCRExecutor: makeSimulation, executeActivity
Logging Library getLogger
Monitor Translation Library DCRTranslator: Constructor, getDCRFromTX, convertToISO8601
Monitor Watchpost Library ContractWatcher: Constructor, startWatching
OS Process Library terminateProcessesByName, terminateProcessByPid, sleep
OS Network Library findFreePorts
Web3 Storage Library getFunctionNameParams, getContractStorageVariableValue
Web3 Deployment Library extractSolcVersion, getSolcVersions, findImports, compileWithVersion, requireFromString, deployContract, getContractABI, retrieveConstructorParameters, createLoggerWeb3, safeStringify

Configuration Library

Source code: lib/config

The Configuration Library provides functions to read and process configuration files for CI and smart contract models. These configurations are stored in YAML format and can be accessed using specific functions within the library.

readCIConfig

Reads the CI configuration from a specified config filename or from the default config.yml.

  • Parameters:
    • configFileName (string, optional): The filename of the configuration file. Default is 'config.yml'.
  • Returns:
    • Object: The CI configuration.

Example Usage:

const { readCIConfig } = require('@lib/config');

// Reading the default config file
const config = readCIConfig();

// Reading a specific config file
const customConfig = readCIConfig('custom_config.yml');

readCIConfigWithPath

Reads the CI configuration from a specified file path.

  • Parameters:
    • configFilePath (string): The file path of the configuration file.
  • Returns:
    • Object: The CI configuration.

Example Usage:

const { readCIConfigWithPath } = require('@lib/config');

// Reading a config file from a specific path
const config = readCIConfigWithPath('../configs/config.yml');

readModelFunctionsParams

Reads the configuration for a given contract and model ID, returning parameter information and their translation to DCR activities and identifier(s).

  • Parameters:
    • contractName (string): The name of the contract.
    • modelId (string): The ID of the model.
    • configFile (string, optional): The filename of the configuration file.
  • Returns:
    • Object: An object containing parameter information and their translation to DCR activities and identifier(s).

Example Usage:

const { readModelFunctionsParams } = require('./config');

// Reading model function parameters from the default config file
const params = readModelFunctionsParams('MyContract', 'Model123');

// Reading model function parameters from a specific config file
const customParams = readModelFunctionsParams('MyContract', 'Model123', 'custom_config.yml');

DCR Information Library

Source code: lib/dcr/info

The DCR Information Library provides functions to fetch and process information from DCR models using specified DCR graph IDs. These functions handle roles, activities, simulations, and other related data, facilitating interaction with the DCR repository.

getRoles

Fetches and returns roles of a DCR model from a specified DCR graph ID.

  • Parameters:
    • dcrID (String): The ID of the DCR graph.
  • Returns:
    • Promise<Array<String>>: A promise that resolves to an array of role names.

Example Usage:

const { getRoles } = require('@lib/dcr/info');

getRoles('dcrGraphId')
  .then(roles => console.log(roles))
  .catch(error => console.error(error));

getActivities

Fetches and returns all activities of a DCR model from a specified DCR graph ID.

  • Parameters:
    • dcrID (String): The ID of the DCR graph.
  • Returns:
    • Promise<Array<String>>: A promise that resolves to an array of activity IDs.

Example Usage:

const { getActivities } = require('@lib/dcr/info');

getActivities('dcrGraphId')
  .then(activities => console.log(activities))
  .catch(error => console.error(error));

getSimulationXML

Fetches and returns the XML representation of a simulation from specified DCR graph and simulation IDs.

  • Parameters:
    • dcrID (String): The ID of the DCR graph.
    • simID (String): The ID of the simulation.
  • Returns:
    • Promise<String>: A promise that resolves to the XML representation of the simulation.

Example Usage:

const { getSimulationXML } = require('@lib/dcr/info');

getSimulationXML('dcrGraphId', 'simulationId')
  .then(xml => console.log(xml))
  .catch(error => console.error(error));

getSimulations

Fetches and returns all simulations in XML format from a specified DCR graph ID.

  • Parameters:
    • dcrID (String): The ID of the DCR graph.
  • Returns:
    • Promise<String>: A promise that resolves to the XML representation of all simulations.

Example Usage:

const { getSimulations } = require('@lib/dcr/info');

getSimulations('dcrGraphId')
  .then(xml => console.log(xml))
  .catch(error => console.error(error));

getLastSimulationId

Fetches all simulations and returns the ID of the last simulation from a specified DCR graph ID.

  • Parameters:
    • dcrID (String): The ID of the DCR graph.
  • Returns:
    • Promise<String>: A promise that resolves to the ID of the last simulation.

Example Usage:

const { getLastSimulationId } = require('@lib/dcr/info');

getLastSimulationId('dcrGraphId')
  .then(lastSimId => console.log(lastSimId))
  .catch(error => console.error(error));

getPendingActivities

Fetches and returns pending activities and their deadlines from a specified DCR graph ID and simulation ID.

  • Parameters:
    • modelID (String): The ID of the DCR model.
    • simID (String): The ID of the simulation.
  • Returns:
    • Promise<Array<Object>>: A promise that resolves to an array of pending activities with their deadlines.

Example Usage:

const { getPendingActivities } = require('@lib/dcr/info');

getPendingActivities('modelId', 'simulationId')
  .then(pendingActivities => console.log(pendingActivities))
  .catch(error => console.error(error));

DCR Execution Library

Source code: lib/dcr/exec

The DCR Execution Library provides functionality to execute activities within DCR models and manage simulations. It uses various utility libraries for authentication, logging, and HTTP requests.

Class: DCRExecutor

makeSimulation

Creates a new simulation for a specified DCR graph ID.

  • Parameters:
    • dcrId (String): The ID of the DCR graph.
  • Returns:
    • Promise<Object>: A promise that resolves to the response object of the simulation creation request.

Example Usage:

const DCRExecutor = require('@lib/dcr/exec');
const executor = new DCRExecutor();

executor.makeSimulation('dcrGraphId')
  .then(response => console.log(response))
  .catch(error => console.error(error));

executeActivity

Executes a specified activity in a simulation of a DCR graph.

  • Parameters:
    • dcrId (String): The ID of the DCR graph.
    • simId (String): The ID of the simulation.
    • activityId (String): The ID of the activity to execute.
    • activityValue (String, optional): The value to pass to the activity.
    • activityType (String, optional): The type of the activity value.
    • dcrRole (String, optional): The role in the DCR model (not currently utilized).
  • Returns:
    • Promise<Object>: A promise that resolves to an object containing the activity ID, execution time, and violation status.

Example Usage:

const DCRExecutor = require('@lib/dcr/exec');
const executor = new DCRExecutor();

executor.executeActivity('dcrGraphId', 'simulationId', 'activityId', 'value', 'type')
  .then(result => console.log(result))
  .catch(error => console.error(error));

Logging Library

Source code: lib/logging/logger.js

The Logging Library provides a utility for logging messages with different levels of severity. It uses the winston logging library and adds colorized console output and file logging.

getLogger

Creates a logger instance for a specified module, with both console and file transports.

  • Parameters:
    • moduleName (String): The name of the module for which the logger is being created. This name is used to name the log file.
  • Returns:
    • Logger: A winston logger instance configured for the specified module.

Example Usage:

const getLogger = require('@lib/logging/logger').getLogger;
const myLogger = getLogger('MyModule');

myLogger.info('This is an info message');
myLogger.error('This is an error message');
myLogger.debug('This is a debug message');

Monitor Translation Library

Source code: lib/monitor/translate

The Monitor Translation Library provides functionality for translating Ethereum transactions into DCR (Dynamic Condition Response) events based on smart contract ABIs and model function parameters.

Class: DCRTranslator

Constructor

Initializes the DCRTranslator class with the provided contract ABI, model function parameters, and web3 instance.

  • Parameters:
    • contractABI (Array): The ABI of the smart contract.
    • modelFunctionParams (Object): The model function parameters.
    • web3 (Object): An instance of Web3.

Example Usage:

const Web3 = require('web3');
const DCRTranslator = require('@lib/monitor/translate');
const contractABI = [...]; // your contract ABI here
const modelFunctionParams = {...}; // your model function parameters here
const web3 = new Web3('http://localhost:8545');

const translator = new DCRTranslator(contractABI, modelFunctionParams, web3);

getDCRFromTX

Translates an Ethereum transaction into DCR events based on the contract ABI and model function parameters.

  • Parameters:
    • tx (Object): The Ethereum transaction object.
    • activities (Array): An array of activity names.
  • Returns:
    • Array<Object>: An array of DCR events or null if no events are found.

Example Usage:

const tx = ... // the retrieved transaction from EVM
const activities = ... // list of activities

const dcrEvents = translator.getDCRFromTX(tx, activities);
console.log(dcrEvents);

convertToISO8601

Converts a value and unit into an ISO 8601 duration string.

  • Parameters:
    • value (Number): The duration value.
    • unit (String): The unit of time ('hours', 'minutes', 'seconds').
  • Returns:
    • String: The ISO 8601 duration string.

Example Usage:

const duration = translator.convertToISO8601(2, 'hours');
console.log(duration); // Outputs: 'PT2H'

Monitor Watchpost Library

Source code: lib/monitor/watchpost

The Monitor Watchpost Library provides functionality to monitor Ethereum smart contracts for new transactions by subscribing to new block headers.

Class: ContractWatcher

Constructor

Initializes the ContractWatcher class with the provided web3 instance, contract address, contract identifier, and contract ABI.

  • Parameters:
    • web3 (Object): An instance of Web3.
    • contractAddress (String): The address of the smart contract.
    • contractIdentifier (String): An identifier for the smart contract.
    • contractABI (Array): The ABI of the smart contract.

Example Usage:

const Web3 = require('web3');
const ContractWatcher = require('@lib/monitor/watchpost');
const web3 = ... // web3 object
const contractAddress = '0xYourContractAddress';
const contractABI = [...]; // your contract ABI here

const watcher = new ContractWatcher(web3, contractAddress, 'YourContractIdentifier', contractABI);

startWatching

Starts monitoring the smart contract for new transactions by subscribing to new block headers.

Example Usage:

watcher.on('newTransaction', (tx) => {
  console.log('New transaction:', tx);
});

watcher.on('error', (error) => {
  console.error('Error:', error);
});

watcher.startWatching();

OS Process Library

Source code: lib/os/process

The OS Process Library provides functions for managing system processes, including terminating processes by name or PID, and introducing delays in execution.

terminateProcessesByName

Terminates all running instances of a process by its name.

  • Parameters:
    • processName (string): The name of the process to terminate.
  • Returns:
    • Promise: Resolves when the processes are terminated.

Warning: This operation is dangerous as it will kill all processes on the platform with the same name. Be cautious when using it to terminate processes in a running test environment.

Example Usage:

const { terminateProcessesByName } = require('@lib/os/process');

terminateProcessesByName('node')
  .then(output => console.log(output))
  .catch(error => console.error(error));

terminateProcessByPid

Terminates a process by its PID.

  • Parameters:
    • pid (number): The PID of the process to terminate.
  • Returns:
    • Promise: Resolves when the process is terminated.

Example Usage:

const { terminateProcessByPid } = require('@lib/os/process');

terminateProcessByPid(12345)
  .then(output => console.log(output))
  .catch(error => console.error(error));

sleep

Introduces a delay in execution for a specified amount of milliseconds.

  • Parameters:
    • ms (number): The number of milliseconds to sleep.
  • Returns:
    • Promise: Resolves after the specified delay.

Example Usage:

const { sleep } = require('@lib/os/process');

async function example() {
  console.log('Start');
  await sleep(2000);
  console.log('End');
}

example();

OS Network Library

Source code: lib/os/network

The OS Network Library provides functionality for network-related operations, such as finding free ports.

findFreePorts

Searches for a specified number of free ports starting from a given port.

  • Parameters:
    • startPort (number): The port number to start the search from.
    • count (number): The number of ports to check for availability.
    • callback (function): Callback function to be invoked once all ports are checked. It receives an array of free ports as its argument.

Example Usage:

const { findFreePorts } = require('@lib/os/network');

findFreePorts(3000, 5, (freePorts) => {
  console.log('Free ports:', freePorts);
});

Web3 Storage Library

Source code: lib/web3/storage

The Web3 Storage Library provides functions for interacting with smart contract storage and decoding transaction data using Web3.

getFunctionNameParams

Decodes and logs the function name and parameters from a transaction event.

  • Parameters:
    • event (Object): The transaction event object.
    • jsonInterface (String): The JSON interface (ABI) of the contract.

Example Usage:

const { getFunctionNameParams } = require('@lib/web3/storage');

const event = { transactionHash: '0x...' }; // Replace with actual transaction hash
const jsonInterface = '[...]'; // Replace with actual contract ABI

getFunctionNameParams(event, jsonInterface);

getContractStorageVariableValue

Fetches the value of a specified storage variable from a contract.

  • Parameters:
    • contract (String): The name of the contract.
    • contractAddress (String): The address of the contract.
    • variableIdentifier (String): The identifier of the storage variable.
  • Returns:
    • Promise<String>: A promise that resolves to the value of the storage variable.

Example Usage:

const { getContractStorageVariableValue } = require('@lib/web3/storage');

const contract = 'MyContract';
const contractAddress = '0x...'; // Replace with actual contract address
const variableIdentifier = 'myVariable';

getContractStorageVariableValue(contract, contractAddress, variableIdentifier)
  .then(value => console.log('Variable value:', value))
  .catch(error => console.error(error));

Web3 Deployment Library

Source code: lib/web3/deploy

The Web3 Deployment Library provides a suite of functions for compiling, deploying, and interacting with Ethereum smart contracts using Web3.

extractSolcVersion

Extracts the Solidity compiler version from the provided source code.

  • Parameters:
    • source (string): The Solidity source code.
  • Returns:
    • string: The extracted Solidity compiler version.
  • Example Usage:
const { extractSolcVersion } = require('@lib/web3/deploy');
const source = 'pragma solidity ^0.8.0;';
const version = extractSolcVersion(source);
console.log(version); // Outputs: '0.8.0'

getSolcVersions

Fetches the available Solidity compiler versions from the official repository.

  • Returns:
    • Promise<Object>: An object containing the available Solidity compiler versions.
  • Example Usage:
const { getSolcVersions } = require('@lib/web3/deploy');
getSolcVersions().then(versions => console.log(versions));

findImports

Callback function to resolve imports when compiling.

  • Parameters:
    • importPath (string): The import path specified in the Solidity smart contract.
  • Returns:
    • string: A string containing the source code of the imported Solidity smart contract.
  • Example Usage:
const { findImports } = require('@lib/web3/deploy');
const source = findImports('openzeppelin/contracts/token/ERC20/ERC20.sol');
console.log(source);

compileWithVersion

Compiles a Solidity contract with a specified version.

  • Parameters:
    • source (string): The Solidity source code.
    • contractFileName (string): The name of the contract file.
    • contractIdentifier (string): The identifier of the contract.
    • version (string): The version of the Solidity compiler.
  • Returns:
    • Promise<Object>: The compiled contract's ABI and bytecode.
  • Example Usage:
const { compileWithVersion } = require('@lib/web3/deploy');
const source = '...'; // Solidity source code
const contractFileName = 'MyContract.sol';
const contractIdentifier = 'MyContract';
const version = '0.8.0';
compileWithVersion(source, contractFileName, contractIdentifier, version)
  .then(compiled => console.log(compiled));

requireFromString

Requires a module from a string source.

  • Parameters:
    • src (string): The module source code as a string.
    • filename (string, optional): The filename for the module.
  • Returns:
    • Object: The exported module object.
  • Example Usage:
const { requireFromString } = require('@lib/web3/deploy');
const moduleSrc = 'module.exports = { test: () => "hello" };';
const myModule = requireFromString(moduleSrc);
console.log(myModule.test()); // Outputs: 'hello'

deployContract

Deploys a contract to the Ethereum network.

  • Parameters:
    • web3 (Object): The Web3 instance.
    • abi (Array): The ABI of the contract.
    • bytecode (string): The bytecode of the contract.
    • envInfo (Object): Environment information including accounts.
    • constructorParameters (Array): The parameters for the contract's constructor.
  • Returns:
    • Promise<Object>: The deployed contract instance.
  • Example Usage:
const { deployContract } = require('@lib/web3/deploy');
const web3 = new Web3('http://localhost:8545');
const abi = [ ... ]; // Contract ABI
const bytecode = '0x...'; // Contract bytecode
const envInfo = { accounts: ['0x...'] };
const constructorParameters = [ ... ];
deployContract(web3, abi, bytecode, envInfo, constructorParameters)
  .then(contract => console.log('Contract deployed at:', contract.options.address));

getContractABI

Generates the ABI (Application Binary Interface) for a given smart contract.

  • Parameters:
    • contractSource (string): The Solidity source code of the contract.
    • contractFileName (string): The name of the smart contract file.
    • contractIdentifier (string): The identifier of the contract.
  • Returns:
    • Promise<Object>: The ABI of the specified smart contract.
  • Example Usage:
const { getContractABI } = require('@lib/web3/deploy');
const contractSource = '...'; // Solidity source code
const contractFileName = 'MyContract.sol';
const contractIdentifier = 'MyContract';
getContractABI(contractSource, contractFileName, contractIdentifier)
  .then(abi => console.log('Contract ABI:', abi));

retrieveConstructorParameters

Retrieves the constructor parameters for a contract.

  • Parameters:
    • constructorParamSpecs (Array): Specifications for the constructor parameters.
    • web3 (Object): The Web3 instance.
    • envInfo (Object): Environment information including accounts.
  • Returns:
    • Promise<Array>: The parameters for the contract's constructor.
  • Example Usage:
const { retrieveConstructorParameters } = require('@lib/web3/deploy');
const constructorParamSpecs = [ ... ];
const web3 = new Web3('http://localhost:8545');
const envInfo = { accounts: ['0x...'] };
retrieveConstructorParameters(constructorParamSpecs, web3, envInfo)
  .then(params => console.log('Constructor Parameters:', params));

createLoggerWeb3

Creates a logger for Web3 interactions.

  • Parameters:
    • web3 (Object): The Web3 instance.
  • Returns:
    • Object: A proxied Web3 instance with logging.
  • Example Usage:
const { createLoggerWeb3 } = require('@lib/web3/deploy');
const web3 = new Web3('http://localhost:8545');
const loggerWeb3 = createLoggerWeb3(web3);
loggerWeb3.eth.getAccounts()
  .then(accounts => console.log('Accounts:', accounts));

safeStringify

Safely stringifies an object to avoid circular references.

  • Parameters:
    • obj (Object): The object to stringify.
  • Returns:
    • string: The stringified object.
  • Example Usage:
const { safeStringify } = require('@lib/web3/deploy');
const obj = { a: 1, b: 2 };
const str = safeStringify(obj);
console.log(str); // Outputs: '{"a":1,"b":2}'