How to use @accordproject/cicero-core - 10 common examples

To help you get started, we’ve selected a few @accordproject/cicero-core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github accordproject / cicero / packages / cicero-test / lib / steps.js View on Github external
* Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const Path = require('path');

const Chai = require('chai');
const expect = Chai.expect;

const Util = require('@accordproject/ergo-test/lib/util');
const Template = require('@accordproject/cicero-core').Template;
const Clause = require('@accordproject/cicero-core').Clause;
const Engine = require('@accordproject/cicero-engine').Engine;

const { Before, Given, When, Then, setDefaultTimeout } = require('cucumber');

// Defaults
const defaultState = {
    '$class':'org.accordproject.cicero.contract.AccordContractState',
    'stateId':'org.accordproject.cicero.contract.AccordContractState#1'
};

/**
 * Initializes the contract
 *
 * @param {object} engine - the Cicero engine
 * @param {object} clause - the clause instance
github accordproject / template-studio / src / TemplateStudio / index.js View on Github external
async loadTemplateFromUrl(templateURL) {
        const thisTemplateURL = templateURL;
        this.setState({ loading: true });
        console.log(`Loading template:  ${thisTemplateURL}`);
        let template;
        try {
            template = await Template.fromUrl(thisTemplateURL);
        } catch (error) {
            console.log(`LOAD FAILED! ${error.message}`); // Error!
            this.handleLoadingFailed(error.message);
            return false;
        }
        try {
            const newState = {...this.state};
            newState.templateURL = thisTemplateURL;
            newState.clause = new Clause(template);
            newState.templateName = newState.clause.getTemplate().getMetadata().getName();
            newState.templateVersion = newState.clause.getTemplate().getMetadata().getVersion();
            newState.templateType = newState.clause.getTemplate().getMetadata().getTemplateType();
            newState.package = JSON.stringify(template.getMetadata().getPackageJson(), null, 2);
            newState.grammar = template.getParserManager().getTemplatizedGrammar();
            newState.model = template.getModelManager().getModels();
            newState.logic = template.getScriptManager().getLogic();
            newState.text = template.getMetadata().getSamples().default;
            newState.request = JSON.stringify(template.getMetadata().getRequest(), null, 2);
            newState.data = 'null';
            this.setState(newState);
            this.setState(Utils.compileLogic(null, this.state.markers, this.state.logic, this.state.clause, this.state.log));
            this.handleModelChange(null, this.state, this.state.model);
            this.handleSampleChangeInit(this.state.text);
            this._handleLogicChange();
            this.handlePackageChange(this.state.package);
github accordproject / template-studio / src / TemplateStudio / index.js View on Github external
async loadTemplateFromBuffer(buffer) {
        this.setState({ loading: true });
        console.log('Loading template from Buffer');
        let template;
        try {
            template = await Template.fromArchive(buffer);
        } catch (error) {
            console.log(`LOAD FAILED! ${error.message}`); // Error!
            this.handleLoadingFailed(error.message);
            return false;
        }
        try {
            const newState = {...this.state};
            newState.clause = new Clause(template);
            newState.templateName = newState.clause.getTemplate().getMetadata().getName();
            newState.templateVersion = newState.clause.getTemplate().getMetadata().getVersion();
            newState.templateType = newState.clause.getTemplate().getMetadata().getTemplateType();
            newState.package = JSON.stringify(template.getMetadata().getPackageJson(), null, 2);
            newState.grammar = template.getParserManager().getTemplatizedGrammar();
            newState.model = template.getModelManager().getModels();
            newState.logic = template.getScriptManager().getLogic();
            newState.text = template.getMetadata().getSamples().default;
            newState.request = JSON.stringify(template.getMetadata().getRequest(), null, 2);
            newState.data = 'null';
            this.setState(newState);
            this.setState(Utils.compileLogic(null, this.state.markers, this.state.logic, this.state.clause, this.state.log));
            this.handleModelChange(null, this.state, this.state.model);
            this.handleSampleChangeInit(this.state.text);
            this._handleLogicChange();
            this.handlePackageChange(this.state.package);
github accordproject / cicero / packages / cicero-cli / lib / commands.js View on Github external
.then(async (template) => {
                // Initialize clause
                clause = new Clause(template);
                clause.parse(sampleText, currentTime);

                let stateJson;
                if(!fs.existsSync(statePath)) {
                    Logger.warn('A state file was not provided, initializing state. Try the --state flag or create a state.json in the root folder of your template.');
                    const initResult = await engine.init(clause, currentTime);
                    stateJson = initResult.state;
                } else {
                    stateJson = JSON.parse(fs.readFileSync(statePath, 'utf8'));
                }

                return engine.invoke(clause, clauseName, paramsJson, stateJson, currentTime);
            })
            .catch((err) => {
github accordproject / cicero / packages / cicero-cli / lib / commands.js View on Github external
.then((template) => {
                // Initialize clause
                clause = new Clause(template);
                clause.parse(sampleText, currentTime);

                return engine.init(clause, currentTime);
            })
            .catch((err) => {
github accordproject / cicero / packages / cicero-cli / lib / commands.js View on Github external
.then(async (template) => {
                // Initialize clause
                clause = new Clause(template);
                clause.parse(sampleText, currentTime);

                let stateJson;
                if(!fs.existsSync(statePath)) {
                    Logger.warn('A state file was not provided, initializing state. Try the --state flag or create a state.json in the root folder of your template.');
                    const initResult = await engine.init(clause, currentTime);
                    stateJson = initResult.state;
                } else {
                    stateJson = JSON.parse(fs.readFileSync(statePath, 'utf8'));
                }

                // First execution to get the initial response
                const firstRequest = requestsJson[0];
                const initResponse = engine.trigger(clause, firstRequest, stateJson, currentTime);
                // Get all the other requests and chain execution through Promise.reduce()
                const otherRequests = requestsJson.slice(1, requestsJson.length);
github accordproject / cicero / packages / cicero-server / app.js View on Github external
app.post('/trigger/:template/:data', async function (req, httpResponse, next) {
    console.log('Template: ' + req.params.template);
    console.log('Clause: ' + req.params.data);
    try {
        const template = await Template.fromDirectory(`${process.env.CICERO_DIR}/${req.params.template}`);
        const data = fs.readFileSync(`${process.env.CICERO_DIR}/${req.params.template}/${req.params.data}`);
        const clause = new Clause(template);
        if(req.params.data.endsWith('.json')) {
            clause.setData(JSON.parse(data.toString()));
        }
        else {
            clause.parse(data.toString());
        }
        const engine = new Engine();
        let result;
        if(Object.keys(req.body).length === 2 &&
           Object.prototype.hasOwnProperty.call(req.body,'request') &&
           Object.prototype.hasOwnProperty.call(req.body,'state')) {
            result = await engine.trigger(clause, req.body.request, req.body.state);
        } else {
            // Add empty state in input, remove it on output
github accordproject / template-studio / scripts / makeArchives.js View on Github external
const packageJson = fs.readFileSync(file, 'utf8');
      const pkgJson = JSON.parse(packageJson);
      if (pkgJson.name !== selectedTemplate) {
        selected = false;
      }
    }

    if (selected) {
      // read the parent directory as a template
      const templatePath = path.dirname(file);
      console.log(`Processing ${templatePath}`);
      const dest = templatePath.replace('/node_modules/@accordproject/cicero-template-library/src/', '/static/');
      await fs.ensureDir(archiveDir);

      try {
        const template = await Template.fromDirectory(templatePath);
        const templateName = template.getMetadata().getName();

        if (!process.env.SKIP_GENERATION && (templateName === 'helloworld' || templateName === 'empty' || templateName === 'empty-contract')) {
          const language = template.getMetadata().getLanguage();
          let archive;
          // Only produce Ergo archives
          if (language === 0) {
            archive = await template.toArchive('ergo');
            const destPath = path.dirname(dest);

            await fs.ensureDir(destPath);
            const archiveFileName = `${template.getIdentifier()}.cta`;
            const archiveFilePath = `${archiveDir}/${archiveFileName}`;
            await writeFile(archiveFilePath, archive);
            console.log(`Copied: ${archiveFileName}`);
          } else {
github accordproject / template-studio / src / TemplateStudio / index.js View on Github external
async loadTemplateFromUrl(templateURL) {
        const thisTemplateURL = templateURL;
        this.setState({ loading: true });
        console.log(`Loading template:  ${thisTemplateURL}`);
        let template;
        try {
            template = await Template.fromUrl(thisTemplateURL);
        } catch (error) {
            console.log(`LOAD FAILED! ${error.message}`); // Error!
            this.handleLoadingFailed(error.message);
            return false;
        }
        try {
            const newState = {...this.state};
            newState.templateURL = thisTemplateURL;
            newState.clause = new Clause(template);
            newState.templateName = newState.clause.getTemplate().getMetadata().getName();
            newState.templateVersion = newState.clause.getTemplate().getMetadata().getVersion();
            newState.templateType = newState.clause.getTemplate().getMetadata().getTemplateType();
            newState.package = JSON.stringify(template.getMetadata().getPackageJson(), null, 2);
            newState.grammar = template.getParserManager().getTemplatizedGrammar();
            newState.model = template.getModelManager().getModels();
            newState.logic = template.getScriptManager().getLogic();
github accordproject / template-studio / src / TemplateStudio / index.js View on Github external
async loadTemplateFromBuffer(buffer) {
        this.setState({ loading: true });
        console.log('Loading template from Buffer');
        let template;
        try {
            template = await Template.fromArchive(buffer);
        } catch (error) {
            console.log(`LOAD FAILED! ${error.message}`); // Error!
            this.handleLoadingFailed(error.message);
            return false;
        }
        try {
            const newState = {...this.state};
            newState.clause = new Clause(template);
            newState.templateName = newState.clause.getTemplate().getMetadata().getName();
            newState.templateVersion = newState.clause.getTemplate().getMetadata().getVersion();
            newState.templateType = newState.clause.getTemplate().getMetadata().getTemplateType();
            newState.package = JSON.stringify(template.getMetadata().getPackageJson(), null, 2);
            newState.grammar = template.getParserManager().getTemplatizedGrammar();
            newState.model = template.getModelManager().getModels();
            newState.logic = template.getScriptManager().getLogic();
            newState.text = template.getMetadata().getSamples().default;