Snippets

chromawallet EsplixIntegration

Created by Riccardo Sibani last modified
import {
    ActionInfo, ActionMatch, ContractDefinition, ContractInstance, EsplixContext, FieldInfo, MultiSigState,
    ParameterInfo, Parameters, ProcessedMessage, PValue, PValueArray, RType
} from "esplix/types/index";
import { isArray } from "util";

export class ContextManager {
    public static context?: EsplixContext;

    public static _init(context: EsplixContext) {
        ContextManager.context = context;
    }

    public static createContract(contractDefinition: ContractDefinition,
                                 parameters: Parameters): Promise<ContractInstance> {
        return this.context!.contractInstanceManager.createContractInstance(contractDefinition, parameters);
    }

    public static getContracts(): ContractInstance[] {
        if (this.context) {
            return this.context.contractInstanceManager.getContractInstances();
        }
        return [];
    }

    public static getContractActions(contract: ContractInstance, pubkeys: any): ActionInfo[] {
        return contract.getApplicableActions().map(
            (match) => contract.getActionInfo(match.name)
        );
    }

    public static contractPerformAction(contract: ContractInstance, action: string, params: Parameters): any {
        return contract.performAction(action, params);
    }

    public static getContractDefinitions(): ContractDefinition[] {
        if (this.context) {
            return this.context.contractDefinitionManager.getAllDefinitions();
        }

        return [];
    }
}

export class AddressBook {
    public addresses: AddressBookEntry[] = [];

    public addAddress(ae: AddressBookEntry) {
        this.addresses.push(ae);
    }

    public getAddresses(): AddressBookEntry[] {
        return this.addresses;
    }

    public searchAddressByPubkey(pubkey: string): AddressBookEntry | null {
        for (let i = 0; i < this.addresses.length; i++) {
            if (pubkey === this.addresses[i].pubkey) {
                return this.addresses[i];
            }
        }

        return null;
    }
}

export interface AddressBookEntry {
    name: string;
    pubkey: string;
}

export interface EsplixKeyPair { // TODO: move to Esplix
    pubKey: string;
    privKey: string;
}

export interface ParameterSimpleProps {
    actionInfo: ActionInfo | null;
    paramInfo: ParameterInfo;
    name: string;
    setParameterValue: (key: string, value: any) => null;
}

export interface ParameterCompositeProps extends ParameterSimpleProps {
    context: EsplixContext; // Esplix context of app
    contract: ContractInstance; // Current contract
}

export interface FileSource {
    fieldName: string;
    action: ActionInfo;
}

export class Helper {
    public static typeIsArray(type: RType): boolean {
        return (!type.isPrimitive) && (isArray(type.typeSpecifier)) && type.typeSpecifier![0] === "ARRAY";
    }

    public static valueIsPubkey(pubkey: string): boolean {
        const pk: Buffer = Buffer.from(pubkey, "hex");

        if (pk && pk.length === 33) {
            return true;
        } else {
            return false;
        }
    }

    public static resolvePubkey(pubkey: Buffer, addressBook: AddressBook): string {
        const entry = addressBook.searchAddressByPubkey(pubkey.toString("hex"));

        if (entry) {
            return entry.name;
        } else {
            return pubkey.toString("hex");
        }
    }

}
import {EsplixContext, postchainConfig} from "esplix";
import barr from "./custom/customer-environment/barr12.r4o.json"; // one contract
import biz from "./custom/customer-environment/barr_biz_contract03.r4o.json"; // another contract
import rup from "./custom/customer-environment/barr_rup02.r4o.json"; // guess? another contract (this is actually the RUP one)

import {ContextManager} from "./defedit"; // this is a small helper, mainly for automatic login

// Secret keypair of each entity (e.g. Chamber of commerce, REUS or PILA)
const rues = {
    privKey: "1773ae49dc342be1038e0fce6ba01a600e20bf251eea00c195173ab3d2ecba27",
    pubKey: "03f2f40d5b1c7ce7a5df46b1c7d2f368959fcbc0fa0203aa2c2d40a69ff7eb6065",
};

// Load the contracts into esplix. (this is needed in order to understand what and how to read and write transactions)
const contractsHex: string[] = [
    biz,
    rup,
    barr,
];

// connection
export async function postchainContext() {
    const config = postchainConfig("http://35.204.193.71:5001/",
        "http://messaging.esplix1.chromaway.net",
        Buffer.from("ae56ed7dc4fb49e6162c7d9ecbb13684928b81f0464d675b23547963700874c7", "hex"));
    const context = new EsplixContext(config);
    await context.initialize();
    // We subscribe only to certain contracts, the one concerns the chamber of commerce demo, for example
    const cdfes = contractsHex.map(
        (ctr) => context.contractDefinitionManager.registerDefinition(Buffer.from(ctr, "hex"))
    );
    return { context, contractDefinition: cdfes[0] };
}

const main = async () => {

    // getting the connection
    const postchain = await postchainContext();
    // Set up into esplix the entity (who is signing?)
    await postchain.context.principalIdentity.importIdentityFromPrivateKey(Buffer.from(rues.privKey, "hex"));
    ContextManager._init(postchain.context);

    // refresh the information, so we get the latest transactions
    await ContextManager.context.update();
    
    // In each contract, we check if the entity can perfom an operation.
    const contracts = ContextManager.getContracts();
    contracts.map((contract) => {
        const actions = ContextManager.getContractActions(contract, Buffer.from(rues.pubKey, "hex"));
        // If yes we can specify behaviours
        actions.map((action) => {
            switch(action) {

              case "ASSIGN_CHAMBER":  // We are looking at this action
                const responsibleChamber = yourFunction(); 
                contract.performAction(action.name, {RESPONSIBLE_CHAMBER_: responsibleChamber});
                break;
              
              case "ANOTHER OPERATION": updateInfoFoo(); break;
              
              default: "Operation not automatically implemented"
            }
        });
    });

};

// Let's do this every 3 seconds
setInterval(main(); }, 3000);

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.