# Smart Contracts Auto-generation for Supply Chain Contexts

Bajeela Aejas, Abdelhak Belhi, Abdelaziz Bouras

► To cite this version:

Bajeela Aejas, Abdelhak Belhi, Abdelaziz Bouras. Smart Contracts Auto-generation for Supply Chain Contexts. 19th IFIP International Conference on Product Lifecycle Management (PLM), Jul 2022, Grenoble, France. pp.347-357, 10.1007/978-3-031-25182-5_34. hal-05420924

HAL Id: hal-05420924

https://inria.hal.science/hal-05420924v1

Submitted on 17 Dec 2025

HAL is a multi-disciplinary open access
archive for the deposit and dissemination of sci-
entific research documents, whether they are pub-
lished or not. The documents may come from
teaching and research institutions in France or
abroad, or from public or private research centers.

L'archive ouverte pluridisciplinaire HAL, est
destinée au dépôt et à la diffusion de documents
scientifiques de niveau recherche, publiés ou non,
émanant des établissements d'enseignement et de
recherche français ou étrangers, des laboratoires
publics ou privés.

<figure><img src="image_1.png" /></figure>

Distributed under a Creative Commons Attribution 4.0 International License
<figure><img src="image_2.png" /></figure>

ifip

International Federation for Information Processing

This document is the original author manuscript of a paper submitted to an IFIP
conference proceedings or other IFIP publication by Springer Nature. As such, there
may be some differences in the official published version of the paper. Such
differences, if any, are usually due to reformatting during preparation for publication or
minor corrections made by the author(s) during final proofreading of the publication
manuscript.
<figure><img src="image_3.png" /></figure>

# Smart Contracts Auto-generation for Supply Chain Contexts

Bajeela A ejas<fnref n="1" />(✉), Abdelhak Belhi<fnref n="2" />, and Abdelaziz Bouras<fnref n="1" />

**Abstract.** The introduction of blockchain technology into Supply Chain management has opened the possibility of faster and more secure transactions of commodities and services. As for every blockchain, Smart Contracts are the tool for controlling the transactions in blockchain-based supply chains. In this paper, we introduce a method for automating the implementation of natural language contracts into Smart Contracts in the Supply Chain context. The basic idea here is to extract information from a natural language contract using two Natural Language Processing (NLP) techniques, the Named Entity Recognition (NER) and Relation Extraction (RE), and then use this extracted information to automatically create a corresponding Smart Contract. This is an ongoing project, and we implemented the first phase of NLP, i.e., NER. The main issue we are facing here is the limited availability of annotated contract datasets. To tackle this challenge, we created an annotated legal contract dataset dedicated to the NER task. The dataset is analyzed with the deep learning method (BiLSTM) and transformer-based method (BERT). As per the generation of smart contracts, our approach consists of identifying meaningful entities and the relations between them and then representing them as business logic that can be directly incorporated into computer code as blockchain smart contracts.

**Keywords:** NLP · NER · RE · Dataset · Deep learning · Legal domain

## 1 Introduction

Irrespectively of its size, any business is supported by the establishment of written contracts. These contracts are created and accepted between the parties involved in the business or any kind of transaction. As the number of involved parties and the size of the business increase, contract management becomes more and more complicated and prone to error. Supply Chain management is one of the largest domains that need to handle numerous contracts every day. As it contains a lot of different types of transactions and actors, the manual management of contracts is very complicated and may lead to conflicts and loss of money and time.

After the rise of the AI era, law firms and other companies are trying to automate
the analysis and management of legal documents such as contracts and court order

<footnote n="1">¹ Computer Science and Engineering, College of Engineering, Qatar University, Doha, Qatar
{ba1901053, abdelaziz.bouras}@qu.edu.qa</footnote>

<footnote n="2">² Joan Bin Jassim Academy for Defence Studies, Al Khor, Qatar</footnote>
documents by making use of various deep learning methods on contract datasets. The automation speeds up the procedures and reduces the risk of conflicts and loss of money that may arise in manual document analysis. Thus, if we can apply the concept of contract management automation in the Supply Chain, it can save a lot of effort, money, and time in the process.

Another emerging technology that shakes different aspects of business and transactions is the blockchain which came to the light in 2009 along with Bitcoin, the first cryptocurrency [1]. Blockchain ensures security and transparency in transactions by providing the concept of immutable and distributed ledgers that are shared between every participant and cannot be manipulated. The transactions and the states are controlled by software scripts called Smart Contracts. All participant nodes must validate the preconditions of the Smart Contract, before its execution. The transactions cannot be changed after the deployment of the Smart Contract.

This paper presents a novel idea for introducing Supply Chain related contract management to the blockchain. The initial step is the automation of contract management by using NLP techniques, Named Entity Recognition (NER) and Relation Extraction (RE). The next phase involves the automatic generation of the Smart Contract based on the extracted results from the initial step. This automatic conversion of natural language contracts to Smart Contracts helps to avoid all the shortcomings of manual contract management in the Supply Chain and provides safer contract management.

The remainder of this paper is organized as follows. In Sect. 2, we explain the Smart Contract lifecycle. Section 3 explains the proposed methodology, Sect. 4 gives a detailed description of the dataset creation. In Sect. 5, we provide some technical details about our methodology to generate Smart Contracts. In Sect. 7 we draw our conclusions and provide some perspectives for future work.

## 2 Smart Contract Life Cycle

This section explains the various stages that the Smart Contract development process goes through. The life cycle of a Smart Contract consists of 4 steps [2, 3], namely creation, deployment, execution and finalization. Figure 1 shows various stages involved in the lifecycle of a Smart Contract.

<figure><img src="image_4.png" /><figcaption>Fig. 1. Accuracy and Loss graph</figcaption></figure>

* **Creation.** In this initial phase, all the parties are involved in the contract negotiated for the obligations and terms. After all the parties reach an agreement, the software
engineers implement the Smart Contract using languages such as JavaScript and Go. After the implementation phase, the parties must validate and agree on the coded version of the Smart Contract.

* **Deployment.** Now, as all the nodes agree, the Smart Contract will be included in the distributed ledger, and thus it gets published on the blockchain. At this phase, the Smart Contract is available to all parties. Once, the Smart Contract got published, no one can modify it. The digital assets of the involved parties are frozen.

* **Execution.** After the deployment, the clauses will be evaluated, to check if the pre-conditions are met. The Smart Contract will be automatically executed once it triggers a condition. Thus, transactions will be added and validated through a consensus protocol.

* **Finalization.** After the execution, the new states of involved parties will be updated. The transactions and states will be stored in the blockchain. The frozen digital assets of the parties will be unblocked, and digital asset transfer will be carried out between the parties.

## 3 Proposed Methodology

The proposed architecture is shown in Fig. 2. Here we are using two NLP techniques for automatically creating Smart Contracts from natural language contracts, namely:

* Named Entity Recognition (NER) and

* Relation Extraction (RE)

<figure><img src="image_5.png" /><figcaption>Fig. 2. Proposed architecture</figcaption></figure>

NER is a method for extracting specific entities from texts such as person, organization, place, date etc. In this case of contracts, we are extracting the legal entities such as parties, effective date, governing law etc. Relation extraction identifies and extracts the relation between the entities. Models created from these methods are used to generate a Smart Contract for the corresponding Supply Chain contract. We are currently working on the NER part that is explained in detail in the upcoming session.
## 3.1 NER and Extracting Entities from Contracts

NER is one of the fundamental tasks of NLP for identifying and extracting generic named entities (NE) such as the name of a person, organization, dates, locations, etc. from the natural language text. The term “Named Entity” was first introduced by R.Grishman and Sundheim [4] in 1996 at the Sixth Message Understanding Conference (MUC-6)<fnref n="1" />. Many NER software tools are available for identifying generic NEs. Some of the most used NER tools available are Stanford NER<fnref n="2" />, OpenNLP<fnref n="3" />, and SpaCy NER<fnref n="4" />. There are many publicly available datasets for generic NER such as MUC-6 [4], CONLL 2002 [5], OntoNotes [6], and WikiNER [7].

NER is also used to recognize domain-specific entities from various domains. For example, identifying entities from historical documents [8], finding protein names from biomedical articles [9], identifying tags like parties, effective date, termination date and governing law [10] from legal documents such as court decisions and contracts. That means the dataset and the entities to be identified completely depend on the specific domain. Thus, the annotation process and entity identification are more difficult in domain-specific NER compared to generic NER.

# 4 A Legal Contract Dataset

The main issue with the NER research in the legal domain is the lack of annotated domain-specific datasets. This negatively impacts the overall research progress in this domain. The main reason for dataset scarcity is the confidentiality nature of the documents [11]. When we take the case of legal contracts, most researchers cannot openly publish datasets due to security and privacy reasons. Realizing the necessity of the task, this paper attempts to manually create an annotated contract dataset for NER and makes it publicly available to help researchers in the field. The natural language contracts for annotation are collected from the public source, the Electronic Data Gathering, Analysis, and Retrieval System (EDGAR)<fnref n="5" /> of the U.S Security and Exchange Commission (SEC).

## 4.1 Structure of the Contract

A contract is a legal document that defines the obligations and rights of the parties involved in the agreement. Contracts usually follow a pattern even though we cannot say it is a perfect template. The size of the contracts varies and depends on the need of parties involved in the agreement. Some contracts are only a few pages long, while others are hundreds of pages long. The first section of the contract is the preamble, which contains the title, the effective date of the contract and the parties involved in the contract with their address. Some contracts may also have a cover page before the preamble with this information along with the table of contents. Recitals or background section gives some

<footnote n="1">¹ https://www-nlpir.nist.gov/relatedProjects/muc/.</footnote>

<footnote n="2">² http://nlp.stanford.edu/software/CRF-NER.shtml.</footnote>

<footnote n="3">³ https://opennlp.apache.org/.</footnote>

<footnote n="4">⁴ http://spacy.io.</footnote>

<footnote n="5">⁵ https://www.sec.gov/edgar/searchedgar/ accessing-edgar-data.htm.</footnote>
background details of the preamble contents. After that, the contract contains articles or sections which mention the clauses. Usually, the first article is "definition" which defines each term clearly. Each article heading mirrors its contents. For example, the termination date will be under the "Termination" clause. To get which country's law the contracts abide by, we need to check the "Governing Law" section. We can also see different heading terms on different contracts. For example, some contracts may use "Applicable Law" instead of "Governing Law". Thus, the legal entities can easily be recognized under the corresponding headings [11].

## 4.2 Dataset Description

Our source of data is a set of natural language contracts. Since we are creating a domain-specific dataset, the corresponding entities are different from normal NEs. To create a dataset, we need to perform various operations that are explained below in detail:

**Collection of Contracts.** We collected different types of publicly available contracts from EDGAR of the U.S. Security and Exchange Commission (SEC). From this collection, 200 contracts have been selected for annotation. The contracts are in pdf format.

**Cleaning and Segmentation.** Before annotating the contracts, we pre-processed the contracts as follows:

1. The pdf contracts are converted to.txt format.

2. The contract files are cleaned Cleaning of text files for minor structural corrections.

3. Documents segmentation to make one sentence per line: the sentence segmentation is performed using SpaCy. Figure 3 shows the number of tokens per sentence in the dataset.

<figure><img src="image_6.png" /><figcaption>Fig. 3. Token length per sentence</figcaption></figure>
<table><caption>**Table 1.** Labels and their descriptions.</caption><thead><tr><td>No</td><td>Label</td><td>Description</td></tr></thead><tbody><tr><td>1</td><td>Title</td><td>Title of the contract usually specifies the type</td></tr><tr><td>2</td><td>Parties</td><td>Parties involved in the agreement</td></tr><tr><td>3</td><td>AgreementDate</td><td>Date on which the contract is signed</td></tr><tr><td>4</td><td>EffectiveDate</td><td>Date from which the contract is effective</td></tr><tr><td>5</td><td>TerminationDate</td><td>Date of termination of the agreement</td></tr><tr><td>6</td><td>TermLength</td><td>Duration in which the contract will be effective</td></tr><tr><td>7</td><td>NotificationPeriod</td><td>Period of notification for termination of the contract</td></tr><tr><td>8</td><td>GoverningLaw</td><td>A country whose laws apply</td></tr><tr><td>9</td><td>Renewal</td><td>Renewal period of the contract</td></tr></tbody></table>

**Selection of Labels.** We selected 9 contract-related labels or tags for annotation. All these labels are very important for contract analysis. Each contract is thoroughly analyzed and annotated with these labels. The tags we selected are shown in Table 1.

**Manual Annotation.** Now the documents are ready for annotation. We used the annotation tool called Datasaur<fnref n="6" /> for annotating the text documents. In this tool, we need to select the NEs and assign the associated NE from the list of NEs. Figure 4 shows the annotation process of a contract from the dataset.

<figure><img src="image_7.png" /><figcaption>**Fig. 4.** Annotated contract from the dataset</figcaption></figure>

On finishing the annotation, the file is ready to be exported to our system. There are different tagging schemes available for annotation. This dataset follows Inside- Outside-Beginning (IOB) [12] format. If an NE contains multiple tokens, each token is annotated with the tag along with prefixes B or I. The B-prefix of a tag indicates that the tag is the beginning of an NE, and the I-prefix indicates that the tag is inside an NE. All the tokens that are not an NE are indicated as “O”.

<footnote n="6">⁶ https://datasaur.ai/.</footnote>
## 4.3 Experiments and Results

We are still working on the annotation of contracts to increase the size of the dataset. The initial dataset is evaluated and compared using the deep learning method, BiLSTM as well as the hugging face transformer model BERT. We opted these two methods as both methods proved their efficiency in providing state of the art result in many NLP datasets. In both experiments, we divided the dataset into 80% training set and 20% test set. The accuracy and loss graphs for training for BiLSTM are shown in Fig. 5 below. Even though accuracy is high, the precision, recall and F1 values for each tag are not that promising in the initial results because of multiple reasons:

* Since the majority of the token in contracts comes under “O” tags, the accuracy can be very high

* Compared to the “O” tags, the remaining labels are very few in number, and the dataset is highly imbalanced. This affects the recall and precision negatively.

<figure><img src="image_8.png" /><figcaption>Fig. 5. Accuracy and loss graph</figcaption></figure>

Table 2 shows the labels that received comparatively higher precision, recall and F1 scores.

## 4.4 Relation Extraction

Like NER, RE is a subtask in NLP that identifies the relationship between different entities in the text. The RE part is very crucial in this process as it is necessary to identify the relation between the entities for creating the conditions in the Smart Contract. As for NER for contracts, RE for contracts also needs a dedicated dataset annotated with required relations. As there are no public datasets available for RE in contracts, we need
<table><caption>**Table 2.** Accuracy, Loss, Precision, Recall and F1 score</caption><thead><tr><th>Method</th><th>Accuracy</th><th>Loss</th><th>Labels</th><th>Precision</th><th>Recall</th><th>F1 score</th></tr></thead><tbody><tr><td rowspan="3">BERT</td><td rowspan="3">0.994</td><td rowspan="3">0.023</td><td>GoverningLaw</td><td>0.70</td><td>0.86</td><td>0.77</td></tr><tr><td>Parties</td><td>0.80</td><td>0.90</td><td>0.85</td></tr><tr><td>Title</td><td>0.70</td><td>0.87</td><td>0.78</td></tr><tr><td rowspan="3">BiLSTM</td><td rowspan="3">0.996</td><td rowspan="3">0.0016</td><td>GoverningLaw</td><td>0.73</td><td>0.70</td><td>0.72</td></tr><tr><td>Parties</td><td>0.79</td><td>0.78</td><td>0.79</td></tr><tr><td>Title</td><td>0.73</td><td>0.80</td><td>0.76</td></tr></tbody></table>

to create one from the scratch and this is going to be our next future task in this ongoing research.

# 5 Generation of Smart Contracts

The overall goal of our research is to generate Smart Contracts based on legal contracts. The task by itself is huge as it involves the translation of business rules written in natural language to computer code. These Smart Contracts will be used in a blockchain network to ensure aspects such as peer-to-peer trust, transparency, tamper-proofness, and security.

We mostly leverage NLP as a tool to analyze raw legal contracts aiming at finding relevant entities and business relation between these entities that may be automatically added as business rules. The idea is that such rules are often straightforward and easy to understand and using an AI-based solution to automatically add them to Supply Chain information systems, with some degree of confidence, will reduce manual modifications and will decrease errors and increase productivity overall.

As per the implementation, at a high level, our solution consists of establishing a common metamodel which represents the different data structures identified following the NER and RE tasks. As an example, all the numerical values or dates, etc. and the rules that define these fields integrity check and constraints. At a subsequent stage, these rules can even be mapped to predefined functions such as payments and penalties which will be directly translated from natural language to Smart Contract code.

Since we intend to use blockchain technology as a platform for both Supply Chain data and business logic, Smart Contracts offer the ability to represent both. One can write object-oriented classes similarly to any language with both data structures and methods or establish relations between these classes.

As per the representation of this information, we rely on a business rules representation which consists of specifying rule conditions and actions in a standardized way. The task consists mostly in translating data field names and types from a JSON representation into real-world actions. In our approach, we rely on a business rules representation framework written initially for Python to make this representation. The task consists of identifying conditions and actions and then populating the generated JSON or XML rule to relevant data models. Figure 6 represents a rule written in JSON and XML that affects product prices based on inventory and expiration dates.
<figure><img src="image_9.png" /><figcaption>**Fig. 6.** An example of a rule definition using our approach (JSON format on the left and XML format on the right)</figcaption></figure>

# 6 Results and Discussion

Following its representation in JSON or XML, the rule is propagated to the established smart contract. The related data model enforced checks related to the rule for records present in the blockchain. For our proof of concept, Fig. 7 and 8 represent a sample of the meta-model file for the rule’s definition. This example rule is an `ONChange` trigger that changes a value to 100 if another value below 5 is given as input.

```json
rules = [
  {
    "conditions": { "all": [
      { "name": "current_value",
        "operator": "less_than",
        "value": 5,
      },
    ]},
    "actions": [
      { "name": "more100",
        "params": {},
      },
    ]
  }
]
```

<caption>**Fig. 7.** Sample of a meta business rule</caption>

```json
async changecustomervalue(ctx, customerNumber, newvalue) {
  console.info('-------------- START : changecustomervalue ---------------');
  const customerAsBytes = await ctx.stub.getstate customerNumber;
  if (!customerAsBytes || customerAsBytes.length === 0) {
    throw new Error('$(customerNumber) does not exist');
  }
  const customer = JSON.parseAsBytes.toString());
  customer.value = newValue;
  if ((parseInt customer.value, 10) < 5 ) {
    console.info('Value less than 5');
    console.info('Customer not created 5');
  }
  else {
    await ctx.stub.putState customerNumber, Buffer.from(JSON.stringify customer));
    console.info('================ END : changecustomerValue================');
  }
}
```

<figure><img src="image_10.png" /><figcaption>**Fig. 9.** Blockchain peers log following the invocation of the Smart Contract `changeValue` method. The reply was that the value was less than 5</figcaption></figure>

Figure 9 shows the Log of one of the blockchain peers following the invocation of the Smart Contract `changeValue` method with a value less than 5 as an argument (Method depicted in Fig. 8).

At the current stage, our approach consists of predefining a set of actions and then mapping NER and RE results, namely data values, condition and action as input to the
smart contract generation process. The process is accurate but further tests need to be
carried on real example as the data we used for our test was synthetically generated due
to the lack of RE results at this stage. We also aim at experimenting with undefined
relations and action in future iterations of this ongoing project.

7 Conclusion

A Supply Chain involves the management of a large number of contracts throughout its lifecycle. Manual contract analysis is very complicated, time-consuming and at the same time may cause conflicts and disputes between the partners. This paper proposes a method to automate and implement the contract management related to Supply Chain in blockchain converting the natural language contracts into Smart Contracts. This extracted information is then used for generating corresponding Smart Contracts. The challenging situation here is the unavailability of annotated contract datasets for both NER and RE tasks. As a first phase of the research, we have manually created a NER dataset using the public contract database, EDGAR. The dataset is being evaluated using BiLSTM and BERT. This is an ongoing project, and the dataset will be widened by annotating more contracts from EDGAR. The next phase is the creation of the RE contract dataset. After the relation extraction model is created, both NER and RE models will be used to create the Smart Contract corresponding to a natural language contract for the Supply Chain.

**Acknowledgement.** This publication was made possible by NPRP grant NPRP11S-1227-170135 from the Qatar National Research Fund (a member of Qatar Foundation). The statements made herein are solely the responsibility of the authors (www.supplyledger.qa).

References

1. Nakamoto, S.: Bitcoin P2P e-cash paper. Mail Arch. 1 (2008)

2. Sillaber, C., Waltl, B.: Life cycle of smart contracts in blockchain ecosystems. Datenschutz und Datensicherheit - DuD 41(8), 497–500 (2017). https://doi.org/10.1007/s11623-017-0819-7

3. Aejas, B., Bouras, A., Belhi, A., Gasmi, H.: Smart Contracts Implementation Based on Bidirectional Encoder Representations from Transformers BT - Product Lifecycle Management. Green and Blue Technologies to Support Smart and Sustainable Organizations. Presented at the (2022). https://doi.org/10.1007/978-3-030-94335-6\_21

4. Grishman, R., Sundheim, B.: Message understanding conference-6: a brief history. In: Proceedings of the 16th Conference on Computational Linguistics, vol. 1, pp. 466–471. Association for Computational Linguistics, USA (1996). https://doi.org/10.3115/992628.992709

5. Tjong Kim Sang, E.F.: Introduction to the coNLL-2002 shared task: language-independent named entity recognition. In: {COLING}-02: The 6th Conference on Natural Language Learning 2002 (CoNLL)-2002) (2002)

6. Weischedel, R., et al.: Ontonotes release 5.0 ldc2013t19. Linguist. Data Consortium, Philadelphia 23 (2013)

7. Nothman, J., Ringland, N., Radford, W., Murphy, T., Curran, J.R.: Learning multilingual named entity recognition from wikipedia. Artif. Intell. **194**, 151–175 (2013). https://doi.org/10.1016/j.artint.2012.03.006
8. Aejas, B., Bouras, A., Belhi, A., Gasmi, H.: Named entity recognition for cultural heritage preservation. In: Belhi, A., Bouras, A., Al-Ali, A.K., Sadka, A.H. (eds.) Data Analytics for Cultural Heritage, pp. 249–270. Springer, Cham (2021). https://doi.org/10.1007/978-3-030-66777-1_11

9. Ramachandran, R., Arutchelvan, K.: Named entity recognition on bio-medical literature documents using hybrid based approach. J. Ambient Intell. Humaniz. Comput. (2021) https://doi.org/10.1007/s12652-021-03078-z

10. Aejas, B., Bouras, A., Belhi, A., Gasmi, H.: A review of contract entity extraction. In: Yang, X.-S., Sherratt, S., Dey, N., Joshi, A. (eds.) Proceedings of Sixth International Congress on Information and Communication Technology. LNNS, vol. 217, pp. 763–771. Springer, Singapore (2022). https://doi.org/10.1007/978-981-16-2102-4_69

11. Chalkidis, I., Androutsopoulos, I., Michos, A.: Extracting contract elements. In: Proceedings of the 16th Edition of the International Conference on Artificial Intelligence and Law, pp. 19–28. Association for Computing Machinery, New York, NY, USA (2017). https://doi.org/10.1145/3086512.3086515

12. Ramshaw, L., Marcus, M.: Text Chunking using Transformation-Based Learning. In: Third Workshop on Very Large Corpora (1995)