How to use fabric-contract-api - 10 common examples

To help you get started, we’ve selected a few fabric-contract-api 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 hyperledger / fabric-chaincode-node / test / chaincodes / annotations / src / test_contract / test_contract.ts View on Github external
await ctx.stub.putState(ctx.stub.createCompositeKey(Asset.stateIdentifier, [asset.id]), Buffer.from(asset.serialize()))
    }

    @Transaction()
    public async updateAsset(ctx: Context, asset: Asset) {
        const existingAsset = await this.getAsset(ctx, asset.id);

        existingAsset.value = asset.value;
        existingAsset.extra.value = asset.extra.value;

        await ctx.stub.putState(ctx.stub.createCompositeKey(Asset.stateIdentifier, [asset.id]), Buffer.from(existingAsset.serialize()))
    }

    @Transaction(false)
    @Returns("Asset")
    public async getAsset(ctx: Context, id: string): Promise {
        const json = await ctx.stub.getState(ctx.stub.createCompositeKey(Asset.stateIdentifier, [id]))

        return Asset.deserialize(json.toString());
    }

    public async ignoreMe(ctx: Context, id: string) {
        // DO NOTHING
    }
    
}
github ampretia / fabric-application-examples / contracts / trade.2 / src / tradecontract.ts View on Github external
public createContext() {
        return new TradeContext();
    }

    /**
     * Instantiate to perform any setup of the ledger that might be required.
     * @param {Context} ctx the transaction context
     */
    @Transaction()
    public async instantiate(ctx): Promise {
        // no implementation required with this example
        // this could be where datamigration is required
        console.log('Instantiate the contract');
    }

    @Transaction()
    public async addCommodity(ctx, commodity: Commodity): Promise {
        console.log(`Adding ${commodity.getDescription()}`);
        await ctx.commodityList.addCommodity(commodity);
        return commodity;
    }

    /**
     * Track the trade of a commodity from one trader to another
     * @param {Context} ctx the transaction context
     * @param {Trade} trade - Object representing the trade (from JSON)
     * @transaction
     */
    @Transaction()
    public async tradeCommodity(ctx, tradingSymbol: string, newOwnerName: string): Promise {

        const commodity = await ctx.commodityList.getCommodity(tradingSymbol);
github ampretia / fabric-application-examples / contracts / trade-ts / dist / lifecyclecontract.js View on Github external
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
// Fabric smart contract classes
const fabric_contract_api_1 = require("fabric-contract-api");
const commoditymgt_1 = require("./commoditymgt");
/**
 * Additional contract within the 'trade-ts' sample that shows a second use of the contract class
 */
class LifecycleContract extends fabric_contract_api_1.Contract {
    constructor() {
        // Unique namespace when multiple contracts per chaincode file
        super('org.example.lifecycle');
    }
    /**
     * Instantiate to perform any setup of the ledger that might be required.
     * @param {Context} ctx the transaction context
     */
    async instantiate(ctx) {
        console.log('Instantiate the contract');
        const mgt = new commoditymgt_1.CommodityManagementContract();
        await mgt.setCommodityDescription(ctx, 'au', 'GOLD');
        await mgt.setCommodityDescription(ctx, 'ag', 'SILVER');
        await mgt.setCommodityDescription(ctx, 'fe', 'IRON');
        await mgt.setCommodityDescription(ctx, 'al', 'ALUMINIUM');
        // need to call the commodity management to establish the trading symbol description mapping
github ampretia / fabric-application-examples / contracts / trade-ts / dist / trade.js View on Github external
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
// Fabric smart contract classes
const fabric_contract_api_1 = require("fabric-contract-api");
const commodity_1 = require("./commodity");
const tradeContext_1 = require("./tradeContext");
/**
 * Define commercial paper smart contract by extending Fabric Contract class
 *
 */
class TradeContract extends fabric_contract_api_1.Contract {
    constructor() {
        // Unique namespace when multiple contracts per chaincode file
        super('org.example.trade');
    }
    /**
     * A custom context provides easy access to list of all trades
     */
    createContext() {
        return new tradeContext_1.default();
    }
    async addCommodity(ctx, commodity) {
        console.log(commodity);
        // const commodity = new Commodity(JSON.parse(commodityJSON));
        // console.log(commodity);
        const key = ctx.stub.createCompositeKey('Commodity', [commodity.getTradingSymbol(), commodity.getTradeId()]);
        console.log(key);
github ampretia / fabric-application-examples / contracts / trade-ts / dist / lifecyclecontract.js View on Github external
* @param {Context} ctx the transaction context
     */
    async instantiate(ctx) {
        console.log('Instantiate the contract');
        const mgt = new commoditymgt_1.CommodityManagementContract();
        await mgt.setCommodityDescription(ctx, 'au', 'GOLD');
        await mgt.setCommodityDescription(ctx, 'ag', 'SILVER');
        await mgt.setCommodityDescription(ctx, 'fe', 'IRON');
        await mgt.setCommodityDescription(ctx, 'al', 'ALUMINIUM');
        // need to call the commodity management to establish the trading symbol description mapping
    }
}
__decorate([
    fabric_contract_api_1.Transaction(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [fabric_contract_api_1.Context]),
    __metadata("design:returntype", Promise)
], LifecycleContract.prototype, "instantiate", null);
exports.LifecycleContract = LifecycleContract;
github ampretia / fabric-application-examples / contracts / cp-ts-extended / src / papernet / papercontract.ts View on Github external
}

        // make sure that the world state has been updated with the new information
        await ctx.cpList.updateState(cp);
        return ctx.returnPaper(cp);
    }

    /**
     * Redeem commercial paper
     * @param {TxContext} ctx the transaction context
     * @param {String} issuer commercial paper issuer
     * @param {Integer} paperNumber paper number for this issuer
     * @param {String} redeemingOwner redeeming owner of paper
     * @param {String} redeemDateTime time paper was redeemed
     */
    @Transaction()
    public async redeem(ctx, issuer, paperNumber, redeemingOwner, redeemDateTime) {

        // Get a key to be used for the paper, and get this from world state
        const cpKey = CommercialPaper.makeKey([issuer, paperNumber]);
        const cp = await ctx.cpList.getPaper(cpKey);

        // Check paper is TRADING, not REDEEMED
        if (cp.isRedeemed()) {
            throw new Error('Paper ' + issuer + paperNumber + ' already redeemed');
        }

        // Verify that the redeemer owns the commercial paper before redeeming it
        if (cp.getOwner() === redeemingOwner) {
            cp.setOwner(cp.getIssuer());
            cp.setRedeemed();
        } else {
github IBM-Blockchain / vehicle-manufacture / contract / src / lib / contracts / vehicle.ts View on Github external
import { Param, Returns, Transaction } from 'fabric-contract-api';
import { Roles } from '../../constants';
import { EventType, HistoricOrder, IVehicleDetails, Order, OrderStatus, Policy, PolicyType, UsageEvent, Vehicle, VehicleStatus } from '../assets'; // tslint:disable-line:max-line-length
import { IOptions } from '../assets/options';
import { Insurer, Manufacturer } from '../organizations';
import { VehicleManufactureNetContext } from '../utils/context';
import { generateId } from '../utils/functions';
import { BaseContract } from './base';

export class VehicleContract extends BaseContract {
    constructor() {
        super('vehicles');
    }

    @Transaction()
    @Returns('Order')
    public async placeOrder(
        ctx: VehicleManufactureNetContext, ordererId: string, vehicleDetails: IVehicleDetails, options: IOptions,
    ): Promise {
        const { participant } = ctx.clientIdentity;

        if (!participant.hasRole(Roles.ORDER_CREATE)) {
            throw new Error(`Only callers with role ${Roles.ORDER_CREATE} can place orders`);
        } else if (participant.orgId !== vehicleDetails.makeId) {
            throw new Error('Callers may only create orders in their organisation');
        }

        const numOrders = await ctx.orderList.count();

        const id = generateId(ctx.stub.getTxID(), 'ORDER_' + numOrders);
github ampretia / fabric-application-examples / contracts / helloworld-ts / src / greetingcontract.ts View on Github external
}

    @Transaction()
    @Returns('Greeting')
    public async getGreeting(ctx: GreetingContext): Promise {
        const log = ctx.logging.getLogger();
        log.info('getGreeting');

        const buffer = await ctx.stub.getState('GREETING');
        const greeting: Greeting = ctx.fromLedgerBuffer(buffer);
        log.info(`getGreeting of ${greeting.getText()}`);
        return greeting;
    }

    @Transaction()
    @Returns('string')
    public async getGreetingText(ctx: GreetingContext): Promise {
        const log = ctx.logging.getLogger();
        log.info('getGreeting');

        const buffer = await ctx.stub.getState('GREETING');
        const greeting: Greeting = ctx.fromLedgerBuffer(buffer);
        log.info(`getGreeting of ${greeting.getText()}`);
        return greeting.getText();
    }

    @Transaction()
    @Returns('string')
    public async paragraph(ctx: GreetingContext): Promise {
        const log = ctx.logging.getLogger();
        log.info('>>>>  About to issue the setGreeting function........');
        // get the greeting
github IBM-Blockchain / vehicle-manufacture / contract / src / lib / contracts / vehicle.ts View on Github external
}

        let query = {};
        if (organization instanceof Manufacturer) {
            query = { selector: { vehicleDetails: { makeId: organization.id } } };
        } else if (organization instanceof Insurer) {
            query = { selector: { id: { $in: (await this.getPolicies(ctx)).map((policy) => policy.vin ) } } };
        }

        const vehicles = await ctx.vehicleList.query(query);

        return vehicles;
    }

    @Transaction(false)
    @Returns('Vehicle')
    public async getVehicle(ctx: VehicleManufactureNetContext, vin: string): Promise {
        const { participant, organization } = ctx.clientIdentity;

        if (!participant.hasRole(Roles.VEHICLE_READ)) {
            throw new Error(`Only callers with role ${Roles.VEHICLE_READ} can get vehicles`);
        }

        const vehicle = await ctx.vehicleList.get(vin);

        if (organization instanceof Manufacturer && !vehicle.madeByOrg(participant.orgId)) {
            throw new Error('Manufacturers may only get a vehicle produced by their organisation');
        }

        // DON'T LIMIT THE INSURER AS WHEN GIVEN A VIN AS PART OF A REQUEST THEY NEED TO SEE THE CAR
        // REMEMBER READ ACCESS CONTROL IN HERE IS JUST AS ITS USEFUL TO THE ORGANISATION IT LIMITS.
        // THEY COULD GET FULL DATA IF THEY WISH AS NO DATA IS PRIVATE
github IBM-Blockchain / generator-fabric / generators / contract / templates / typescript / src / my-contract.ts View on Github external
/*
 * <%= spdxAndLicense // SPDX-License-Identifier: Apache-2.0 %>
 */

import { Context, Contract, Info, Returns, Transaction } from 'fabric-contract-api';
import { MyAsset } from './my-asset';

@Info({title: 'MyContract', description: '<%= description %>' })
export class MyContract extends Contract {

    @Transaction(false)
    @Returns('boolean')
    public async assetExists(ctx: Context, assetId: string): Promise {
        const buffer = await ctx.stub.getState(assetId);
        return (!!buffer && buffer.length > 0);
    }

    @Transaction()
    public async createAsset(ctx: Context, assetId: string, value: string): Promise {
        const exists = await this.assetExists(ctx, assetId);
        if (exists) {
            throw new Error(`The asset ${assetId} already exists`);
        }
        const asset = new MyAsset();
        asset.value = value;
        const buffer = Buffer.from(JSON.stringify(asset));
        await ctx.stub.putState(assetId, buffer);
    }