How to use the fabric-contract-api.Returns 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 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 / 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);
    }
github ampretia / fabric-application-examples / contracts / helloworld-ts / src / greetingcontract.ts View on Github external
}

    @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
        const res = await ctx.stub.invokeChaincode('helloneta', ['setGreetingText', 'Dear Sidney'], 'mychannel');
        log.info('>>>>  Returned.....  ........');
        const text = `${res} Sorry for not putting beak to paper sooner. `;
        return text;
    }
}
github IBM-Blockchain / vehicle-manufacture / contract / src / lib / contracts / vehicle.ts View on Github external
const order = await ctx.orderList.get(orderId);

        if (!order.madeByOrg(participant.orgId)) {
            throw new Error('Callers may only schedule an order in their organisation for manufacture');
        }

        order.orderStatus = OrderStatus.SCHEDULED_FOR_MANUFACTURE;
        await ctx.orderList.update(order);

        ctx.setEvent('UPDATE_ORDER', order);
        return order;
    }

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

        if (
            !participant.hasRole(Roles.ORDER_UPDATE) ||
            !participant.hasRole(Roles.VEHICLE_CREATE)
        ) {
            throw new Error(
                `Only callers with roles ${Roles.ORDER_UPDATE} and ${Roles.VEHICLE_CREATE} can register vehicles for orders` // tslint:disable-line
            );
        } else if (!(organization as Manufacturer).originCode || !(organization as Manufacturer).manufacturerCode) {
            throw new Error(
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 {
        const log = ctx.logging.getLogger();
github IBM-Blockchain / vehicle-manufacture / contract / src / lib / contracts / vehicle.ts View on Github external
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)
    @Returns('UsageEvent[]')
github IBM-Blockchain / vehicle-manufacture / contract / src / lib / contracts / vehicle.ts View on Github external
const numPolicies = await ctx.policyList.count();

        const id = generateId(ctx.stub.getTxID(), 'POLICY_' + numPolicies);
        const startDate = (ctx.stub.getTxTimestamp().getSeconds() as any).toInt() * 1000;

        const policy = new Policy(id, vin, participant.orgId, holderId, policyType, startDate, endDate);

        await ctx.policyList.add(policy);

        ctx.setEvent('CREATE_POLICY', policy);

        return policy;
    }

    @Transaction(false)
    @Returns('Policy[]')
    public async getPolicies(ctx: VehicleManufactureNetContext) {
        const { participant, organization } = ctx.clientIdentity;

        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;
    }
github IBM-Blockchain / generator-fabric / generators / contract / templates / typescript / src / my-contract.ts View on Github external
}

    @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);
    }

    @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`);
        }