Rule-based smart contract
Smart contracts a rule-based systems. The Second State smart contract platform supports a formal rules language inside smart contracts. The rules language makes it easy to write rigorous and correct smart contracts, and in turn, smart contracts make business rules transparent and more collaborative. The complete source code for this example is available here.
Access the BUIDL IDE from your browser: https://buidl.secondstate.io/
Let’s first see how the DApp works. It show a contract that calculates rebates for a customer based on rules. The customer gets 5% rebate, up to $100, for every purchase that is $100 or more. You can click on the Add button to simulate a purchase made by this user. The contract automatically computes the rebate as soon as a new purchase is made.
Step 1: Copy and paste the following code into contract tab
The important code segment is at the end of the contract, where we specify how the rebates should be given in a set of formal rules named computeRebate
. The contract uses factInsert
, factDelete
, and fireAllRules
built-in functions to manage the data and execution of this rule. For more details, you can read the Lity rules documentation.
Compile and deploy the smart contract via the Compile and Deploy buttons. Notice that the contract requires a constructor parameter. The parameter is a person's name. This contract represents his or her shopping history.
Step 2: Copy and paste the follow HTML code into the dapp -> HTML tab
The HTML page presents a UI that allows users to add purchases for this person. With each purchase, the rebate is re-calculated according to the rule.
Step 3: Copy and paste the following into the dapp -> JS tab
BUIDL pre-fills the JavaScript with the smart contract's compiled artifacts (ABI and bytecode), and its deployed address on the blockchain. The script starts by making a getInfo()
call against the contract instance (i.e., a person) via web3 to get the current state of the contract.
The buy()
method prompts the user to enter a purchase amount to add to this person. It waits for 2 seconds and then calls getInfo()
again to get the updated purchase and rebate information for this person from the blockchain smart contract.
Step 4: Hit the Run button to launch the DApp
You will see the web app running inside the right panel. You can now add purchases to the person, and see his or her rebates change.
There is also a more complex example of the rebate rules, which allows you to create new persons (one contract per person), and then manage all persons in a table. Try the source code here.
Last updated