Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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
}
}
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);
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
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);
* @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;
}
// 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 {
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);
}
@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
}
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
/*
* <%= 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);
}