Introduced fallback contract execution (#388)

This commit is contained in:
Chalith Desaman
2023-11-08 10:24:15 +05:30
committed by GitHub
parent bfc38a3c70
commit c3bacabff6
25 changed files with 377 additions and 126 deletions

View File

@@ -5,10 +5,10 @@ const exectsFile = "exects.txt";
// HP smart contract is defined as a function which takes HP ExecutionContext as an argument.
// HP considers execution as complete, when this function completes and all the NPL message callbacks are complete.
const echoContract = async (ctx) => {
const contract = async (ctx, readonly = false) => {
// We just save execution timestamp as an example state file change.
if (!ctx.readonly) {
if (!readonly) {
fs.appendFileSync(exectsFile, "ts:" + ctx.timestamp + "\n");
const stats = fs.statSync(exectsFile);
@@ -56,7 +56,7 @@ const echoContract = async (ctx) => {
// ctx.unl.find("<public key hex>");
// NPL messages example.
// if (!ctx.readonly) {
// if (!readonly) {
// // Start listening to incoming NPL messages before we send ours.
// const promise = new Promise((resolve, reject) => {
// let timeout = setTimeout(() => {
@@ -84,5 +84,33 @@ const echoContract = async (ctx) => {
// await ctx.updateConfig(config);
}
const fallback = async (ctx) => {
console.log(`Fallback mode: Non consensus execution count: ${ctx.nonConsensusRounds}`);
// NPL messages example.
// Start listening to incoming NPL messages before we send ours.
const promise = new Promise((resolve, reject) => {
let timeout = setTimeout(() => {
reject('NPL timeout.');
}, 2000);
let list = [];
ctx.unl.onMessage((node, msg) => {
console.log(`${node.publicKey} said ${msg} to me.`);
list.push(msg);
if (list.length == ctx.unl.list().length) {
clearTimeout(timeout);
resolve();
}
});
});
await ctx.unl.send("Hello");
await promise;
}
const hpc = new HotPocket.Contract();
hpc.init(echoContract);
hpc.init({
"consensus": async (ctx) => { await contract(ctx, false); },
"consensus_fallback": async (ctx) => { await fallback(ctx); },
"read_req": async (ctx) => { await contract(ctx, true); }
});