How to use the fabric-contract-api.Transaction function in fabric-contract-api

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 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 / 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 / custom-serializer / src / my-contract.ts View on Github external
* the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Context, Contract, Returns, Transaction } from 'fabric-contract-api';

export class MyContract extends Contract {

    @Transaction()
    public async instantiate(ctx: Context): Promise {
        const greeting = { text: 'Hi' };
        await ctx.stub.putState('GREETING', Buffer.from(JSON.stringify(greeting)));
        console.info('Set the default greeting');
    }

    @Transaction()
    public async setGreetingText(ctx: Context, text: string): Promise {
        const greeting = { text };
        await ctx.stub.putState('GREETING', Buffer.from(JSON.stringify(greeting)));
        console.info(`setGreeting to ${greeting.text}`);
    }

    @Transaction()
    @Returns('object')
    public async getGreeting(ctx: Context): Promise {
github ampretia / fabric-application-examples / contracts / custom-serializer / src / my-contract.ts View on Github external
* See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Context, Contract, Returns, Transaction } from 'fabric-contract-api';

export class MyContract extends Contract {

    @Transaction()
    public async instantiate(ctx: Context): Promise {
        const greeting = { text: 'Hi' };
        await ctx.stub.putState('GREETING', Buffer.from(JSON.stringify(greeting)));
        console.info('Set the default greeting');
    }

    @Transaction()
    public async setGreetingText(ctx: Context, text: string): Promise {
        const greeting = { text };
        await ctx.stub.putState('GREETING', Buffer.from(JSON.stringify(greeting)));
        console.info(`setGreeting to ${greeting.text}`);
    }

    @Transaction()
    @Returns('object')
    public async getGreeting(ctx: Context): Promise {
        const buffer = await ctx.stub.getState('GREETING');
        const greeting = JSON.parse(buffer.toString());
        console.info(`getGreeting of ${greeting.text}`);
        return greeting;
    }

}
github IBM-Blockchain / vehicle-manufacture / contract / src / lib / contracts / vehicle.ts View on Github external
public async getUsageEvents(ctx: VehicleManufactureNetContext): Promise {
        const { participant} = ctx.clientIdentity;

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

        const vehicles = await this.getVehicles(ctx);

        const usageEvents: UsageEvent[][] = await Promise.all(vehicles.map((vehicle) => {
            return this.getVehicleEvents(ctx, vehicle.id);
        }));
        return [].concat.apply([], usageEvents);
    }

    @Transaction(false)
    @Returns('UsageEvent[]')
    public async getVehicleEvents(ctx: VehicleManufactureNetContext, vin: string): Promise {
        await this.getVehicle(ctx, vin);

        const { participant } = ctx.clientIdentity;

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

        const usageEvents = await ctx.usageList.query({selector: {vin}});

        return usageEvents;
    }

    @Transaction(false)
github IBM-Blockchain / vehicle-manufacture / contract / src / lib / contracts / vehicle.ts View on Github external
if (!participant.hasRole(Roles.POLICY_READ)) {
            throw new Error(`Only callers with role ${Roles.POLICY_READ} can read policies`);
        }

        let query = {};
        if (organization instanceof Insurer) {
            query = { selector: { insurerId: organization.id } };
        }

        const policies = await ctx.policyList.query(query);

        return policies;
    }

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

        if (!participant.hasRole(Roles.POLICY_READ)) {
            throw new Error(`Only callers with role ${Roles.POLICY_READ} can read policies`);
        }

        const policy = await ctx.policyList.get(policyId);

        if (organization instanceof Insurer && policy.insurerId !== organization.id) {
            throw new Error('Only insurers who insure the policy can view it');
        }

        return policy;
    }
github ampretia / fabric-application-examples / contracts / helloworld-ts / src / greetingcontract.ts View on Github external
/**
     * Define a custom context for commercial paper
     */
    public createContext() {
       return new GreetingContext();
    }

    @Transaction()
    public async instantiate(ctx: GreetingContext): Promise {
        const greeting = { text: 'Hi' };
        await ctx.stub.putState('GREETING', Buffer.from(JSON.stringify(greeting)));
        const log = ctx.logging.getLogger();
        log.info('Set the default greeting');
    }

    @Transaction()
    @Returns('Greeting')
    public async setGreetingText(ctx: GreetingContext, text: string): Promise {
        const log = ctx.logging.getLogger();
        log.info('setGreetingText');
        const greeting: Greeting = new Greeting(text);

        log.info('Created greeting');

        await ctx.stub.putState('GREETING', ctx.toLedgerBuffer(greeting));
        log.info('put the greeting to the ledger');

        return greeting;
    }

    @Transaction()
    public async setGreeting(ctx: GreetingContext, greeting: Greeting): Promise {
github IBM-Blockchain / vehicle-manufacture / contract / src / lib / contracts / vehicle.ts View on Github external
@Returns('Order[]')
    public async getOrders(ctx: VehicleManufactureNetContext): Promise {
        const { participant, organization } = ctx.clientIdentity;
        if (!participant.hasRole(Roles.ORDER_READ)) {
            throw new Error(`Only callers with role ${Roles.ORDER_READ} can read orders`);
        }

        let query = {};
        if (organization instanceof Manufacturer) {
            query = { selector: { vehicleDetails: { makeId: organization.id } } };
        }

        return await ctx.orderList.query(query);
    }

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

        if (!participant.hasRole(Roles.ORDER_READ)) {
            throw new Error(`Only callers with role ${Roles.ORDER_READ} can read orders`);
        }

        const order = await ctx.orderList.get(orderId);

        if (organization instanceof Manufacturer && !order.madeByOrg(participant.orgId)) {
            throw new Error(
                'Manufacturers may only read an order made by their organisation',
            );
        }
github IBM-Blockchain / generator-fabric / generators / contract / templates / typescript / src / my-contract.ts View on Github external
await ctx.stub.putState(assetId, buffer);
    }

    @Transaction(false)
    @Returns('MyAsset')
    public async readAsset(ctx: Context, assetId: string): Promise {
        const exists = await this.assetExists(ctx, assetId);
        if (!exists) {
            throw new Error(`The asset ${assetId} does not exist`);
        }
        const buffer = await ctx.stub.getState(assetId);
        const asset = JSON.parse(buffer.toString()) as MyAsset;
        return asset;
    }

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

    @Transaction()
    public async deleteAsset(ctx: Context, assetId: string): Promise {
        const exists = await this.assetExists(ctx, assetId);
        if (!exists) {
            throw new Error(`The asset ${assetId} does not exist`);