Cannot submit a transcation in composer playground? - hyperledger

Problem:
I have created and deployed a business network in https://composer-playground.mybluemix.net. There I can create participant and assets as I expected. But Submit Transaction button is disable.
This is my .cto file.Where I wrote business network model.
namespace org.landreg
abstract concept Address {
o String addressLine
o String locality
}
concept DutchAddress {
o String postalCode regex=/\d{4}[ ]??[A-Z]{2}/
}
enum Gender {
o FEMALE
o MALE
}
participant Individual identified by passportNumber{
o String passportNumber
o DutchAddress address
o Gender gender
}
asset LandTitle identified by id {
o String id
o DutchAddress address
o Integer area range=[1000,]
o Boolean forSale default=false
o Double price optional
--> Individual owner
--> Individual[] previousOwners
}
abstract transaction UnlockLandTitle {
-->LandTitle landTitle
}
This is my logic.js file.Where I define the transaction.
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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.
*/
"use strict";
/**
* Write your transction processor functions here
*/
const NS = "org.landreg";
/**
* Sample transaction
* #param {org.landreg.UnlockLandTitle} tx //transaction object define in the cto file
* #transaction
*/
async function UnlockLandTitle(tx) {
//Get asset registery for landTitles
const landTitleRegistry = await getAssetRegistry(NS + ".LandTitle");
if (tx.landTitle.forSale) {
throw new Error(
`Land Title with id ${tx.landTitle.getIdentifier()} is already unlocked for sale`
);
}
// Unlock asset to be for sale
tx.landTitle.forSale = true;
await landTitleRegistry.update(tx.landTitle);
}
Can someone help me to solve this problem? Because without solving this I cannot go forward.I search and try to solve this problem.But I was unable to find any solution for this problem.Thank You!

The problem is in your Model(.cto) file.
You can not use abstract with transaction, just remove abstract keyword.
transaction UnlockLandTitle {
--> LandTitle landTitle
}

Related

Reading address from environmental variable or hardhat

I'm new at solidity.
I've put here the snippet of code:
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract Example {
AggregatorV3Interface internal priceFeed;
/**
* Network: Goerli
* Aggregator: ETH/USD
* Address: 0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
*/
constructor() {
priceFeed = AggregatorV3Interface(
0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
);
owner = msg.sender;
}
}
And if you see, the parameter that I need to send to AggregatorV3Interface is static 0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e.
To me, that doesn't look optimized enough. Because right now, I'm playing with this function for Goerli, but if I were to deploy this contract to Etherium mainnet, I would have to change that address manually. Even if you go to chainlink website, they have it like this. https://docs.chain.link/data-feeds/price-feeds/#solidity
Is there a better way? I would like to have some variable that I would set, and read from it? Or maybe some custom variable setting from hardhat, that I'm using.
priceFeed = AggregatorV3Interface(env.proccess.address); Would be desired, or anything dynamic.
Usual approach is to pass the address to Solidity constructor from a JS (or any other offchain language) script that reads from the environment variable.
.env
AGGREGATOR_ADDRESS=0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
JS deployer script
require("dotenv").config();
const hre = require("hardhat");
async function main() {
const factory = await hre.ethers.getContractFactory("Example");
// pass constructor arguments to the `deploy()` function
const contract = await factory.deploy(process.env.AGGREGATOR_ADDRESS);
await contract.deployed();
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Solidity contract
pragma solidity ^0.8;
import "#chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract Example {
AggregatorV3Interface internal priceFeed;
constructor(address _aggregator) {
priceFeed = AggregatorV3Interface(_aggregator);
}
}

"expected primary expression" error - Trying to compile a smart contract on remix - ethereum ide

I'm being honest this code is taken from a website that is supposed to ease the creation of a smart contract/token on the binance smart chain. (short backstory: Me and some friends thought it would be fun to have our own token to e.g. take bets, play poker whatsoever and are now trying to create our own through deploying our smart contract on the BSC)
Here is a link to the template I used: https://github.com/binance-chain/bsc-genesis-contract/blob/master/contracts/bep20_template/BEP20Token.template
I am trying to compile the code but in line 352 the error "expected primary expression" occurs. What does that mean? I am really just a layman. The token is supposed to be called Omega and the Symbol OHM.
Thank you for your suggestions!
The linked contract contains this function which causes the syntax error.
constructor() public {
_name = {{TOKEN_NAME}};
_symbol = {{TOKEN_SYMBOL}};
_decimals = {{DECIMALS}};
_totalSupply = {{TOTAL_SUPPLY}};
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
I'm assuming that it was the contract author's intention to use these placeholders as a way to point out where you can fill in your own values.
After you replace the placeholders with real values, the contract compiles successfully.
constructor() public {
_name = "MyToken";
_symbol = "MyT";
_decimals = 18;
_totalSupply = 1000000000000000000;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}

Attaching a subscriber/listener within EPL module to a statement with context partitions

I have the following EPL module which successfully deploys:
module context;
import events.*;
import configDemo.*;
import annotations.*;
import main.*;
import subscribers.*;
import listeners.*;
#Name('schemaCreator')
create schema InitEvent(firstStock String, secondStock String, bias double);
#Name('createSchemaEvent')
create schema TickEvent as TickEvent;
#Name('contextCreator')
create context TwoStocksContext
initiated by InitEvent as initEvent;
#Name('compareStocks')
#Description('Compare the difference between two different stocks and make a decision')
#Subscriber('subscribers.MySubscriber')
context TwoStocksContext
select * from TickEvent
match_recognize (
measures A.currentPrice as a_currentPrice, B.currentPrice as b_currentPrice,
A.stockCode as a_stockCode, B.stockCode as b_stockCode
pattern (A C* B)
define
A as A.stockCode = context.initEvent.firstStock,
B as A.currentPrice - B.currentPrice >= context.initEvent.bias and
B.stockCode = context.initEvent.secondStock
);
I have a problem with the listeners/subscribers. According to my checks and debugging, the classes don't have any problems, the annotations work, they are attached to the statement upon deployment, and yet neither of them receive any updates from the events.
This is my subscriber, I simply want to print that it has been received:
package subscribers;
import java.util.Map;
public class MySubscriber {
public void update(Map row) {
System.out.println("got it");
}
}
I previously had the same module without any context partitions and then the subscribers worked without a problem. After I added the context, it stopped.
So far I have tried:
Checking if the statement has any subscriber/listener attached (it does)
Checking their names
Remove the annotations and set them manually within Java code after deployment (same thing - they attach, I can retrieve their name but still don't receive updates)
Debugging the subscriber class. The program either doesn't go there at all to stop at a break point or I get an error (missing line number attribute error - ("can't place a break point there" which I tried to fix to no avail)
Any idea what could cause this or what is the best way to set a subscriber to a statement which has context partitions?
This is a continuation of a previous problem which was solved here - Creating instances of Esper's epl
EDIT: Events being sent in the format I use them and in the EPL online tool format:
I first get the pair to be followed from the user:
System.out.println("First stock:");
String first = scanner.nextLine();
System.out.println("Second stock:");
String second = scanner.nextLine();
System.out.println("Difference:");
double diff= scanner.nextDouble();
InitEvent init = new InitEvent(first, second, diff);
After that I have an engine thread the continuously sends events, but before it starts InitEvents is sent as such:
#Override
public void run() {
runtime.sendEvent(initEvent);
while (contSimulation) {
TickEvent tick1 = new TickEvent(Math.random() * 100, "YAH");
runtime.sendEvent(tick1);
TickEvent tick2 = new TickEvent(Math.random() * 100, "GOO");
runtime.sendEvent(tick2);
TickEvent tick3 = new TickEvent(Math.random() * 100, "IBM");
runtime.sendEvent(tick3);
TickEvent tick4 = new TickEvent(Math.random() * 100, "MIC");
runtime.sendEvent(tick4);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
latch.countDown();
}
}
I haven't used the online tool before but I think I got it working. This is the module text:
module context;
create schema InitEvent(firstStock String, secondStock String, bias double);
create schema TickEvent(currentPrice double, stockCode String);
create context TwoStocksContext
initiated by InitEvent as initEvent;
context TwoStocksContext
select * from TickEvent
match_recognize (
measures A.currentPrice as a_currentPrice, B.currentPrice as b_currentPrice,
A.stockCode as a_stockCode, B.stockCode as b_stockCode
pattern (A C* B)
define
A as A.stockCode = context.initEvent.firstStock,
B as A.currentPrice - B.currentPrice >= context.initEvent.bias and
B.stockCode = context.initEvent.secondStock
);
And the sequence of events:
InitEvent={firstStock='YAH', secondStock = 'GOO', bias=5}
TickEvent={currentPrice=55.6, stockCode='YAH'}
TickEvent={currentPrice=50.4, stockCode='GOO'}
TickEvent={currentPrice=30.8, stockCode='MIC'}
TickEvent={currentPrice=24.9, stockCode='APP'}
TickEvent={currentPrice=51.6, stockCode='YAH'}
TickEvent={currentPrice=45.8, stockCode='GOO'}
TickEvent={currentPrice=32.8, stockCode='MIC'}
TickEvent={currentPrice=28.9, stockCode='APP'}
The result I get using them:
At: 2001-01-01 08:00:00.000
Statement: Stmt-4
Insert
Stmt-4-output={a_currentPrice=55.6, b_currentPrice=50.4, a_stockCode='YAH',
b_stockCode='GOO'}
At: 2001-01-01 08:00:00.000
Statement: Stmt-4
Insert
Stmt-4-output={a_currentPrice=51.6, b_currentPrice=45.8, a_stockCode='YAH',
b_stockCode='GOO'}
If I make the second set of events having a difference less than 5 between YAH/GOO, I only get output from the first pair which makes sense. This is, I think what it is supposed to do.
In case needed, those two methods read and process the annotations of the EPL module (I didn't write them myself, they are taken from coinTrader Context class that could be found here - https://github.com/timolson/cointrader/blob/master/src/main/java/org/cryptocoinpartners/module/Context.java ):
private static Object getSubscriber(String className) throws Exception {
Class<?> cl = Class.forName(className);
return cl.newInstance();
}
private static void processAnnotations(EPStatement statement) throws Exception {
Annotation[] annotations = statement.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof Subscriber) {
Subscriber subscriber = (Subscriber) annotation;
Object obj = getSubscriber(subscriber.className());
System.out.println(subscriber.className());
statement.setSubscriber(obj);
} else if (annotation instanceof Listeners) {
Listeners listeners = (Listeners) annotation;
for (String className : listeners.classNames()) {
Class<?> cl = Class.forName(className);
Object obj = cl.newInstance();
if (obj instanceof StatementAwareUpdateListener) {
statement.addListener((StatementAwareUpdateListener) obj);
} else {
statement.addListener((UpdateListener) obj);
}
}
}
}
}
Well, after a month of struggle I finally solved it. In case anyone has similar problem in the future, here's where the problem was. The epl worked fine in the online tool but not in my code. Eventually, I figured out initial events aren't firing, hence context partitions aren't being created and as a result the subscribers and listeners do not receive any updates. My mistake was that I had POJO InitEvent fired, but the event that the context was using was created within the EPL module via create schema. I don't know what I was thinking, it makes sense now that it didn't work. As a result, the events I fire within Java aren't the events that the context uses. My solution was only within the EPL. Since I couldn't figure out if I can fire events in Java that are created within the module, I created a schema which is populated by my POJO and the stream is then used by the context as such:
#Name('schemaCreator')
create schema StartEvent(firstStock string, secondStock string, difference
double);
#Name('insertInitEvent')
insert into StartEvent
select * from InitEvent;
All else remains the same, as well as the Java code.

Pass variable into global scope and determine if query output is null Laravel

I've translation models and I want to run Global query scope that determine the current locale and return the corresponding value upon it or fall back into English if the translation doesn't exist in DB.
I've created a global scope for this purpose and its running good without the ability to fall back into English, so some pages crashes since I'm trying to get property of NULL, and I tried passing some value, but inside the builder I can't determine if the query is going to return null.
How may achieve such thing in Laravel?
my code as follows:
trait WhereLanguage {
/**
* Boot the Where Language trait for a model.
*
* #return void
*/
public static function bootWhereLanguage()
{
static::addGlobalScope(new WhereLanguageScope);
}
}
and the Scope file:
class WhereLanguageScope implements ScopeInterface {
/**
* Apply the scope to a given Eloquent query builder.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #param \Illuminate\Database\Eloquent\Model $model
*/
public function apply(Builder $builder, Model $model)
{
$this->addWhereLang($builder);
}
/**
* Remove the scope from the given Eloquent query builder.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #param \Illuminate\Database\Eloquent\Model $model
*
* #return void
*/
public function remove(Builder $builder, Model $model)
{
$query = $builder->getQuery();
foreach ((array) $query->wheres as $key => $where)
{
// If the where clause is a soft delete date constraint, we will remove it from
// the query and reset the keys on the wheres. This allows this developer to
// include deleted model in a relationship result set that is lazy loaded.
if ($where['column'] == 'lang_id')
{
unset($query->wheres[$key]);
$query->wheres = array_values($query->wheres);
}
}
}
/**
* Extend Builder with custom method.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
*
*/
protected function addWhereLang(Builder $builder)
{
$builder->macro('whereLang', function(Builder $builder)
{
// here 1 is ID for English,
// 48 Arabic, 17 Netherlands...etc
// and It was the App:currentlocale() passed into Language model to determine the ID of current locale.
// but for testing now I hard coded it with ID of 48
$builder->where('lang_id','=','48');
return $builder;
});
}
}
Usage example:
$title = $centre->translations()->whereLang()->first()->name;
Where Centre is my model without localization, and translation is the name of method that handling the relation between Centre & CentreTranslation.
btw I don't want to pass variable obligately.

Jenkins HelloWorld plugin does not persist config after restart

I have been trying to create my first jenkins plugin. Everything is great except that the global config does not persist after the jenkins service is restarted.
THe config saves fine as long as the service is not restarted.
The global config jelly file...
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define" xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
Jenkins uses a set of tag libraries to provide uniformity in forms.
To determine where this tag is defined, first check the namespace URI,
and then look under $JENKINS/views/. For example, <f:section> is defined
in $JENKINS/views/lib/form/section.jelly.
It's also often useful to just check other similar scripts to see what
tags they use. Views are always organized according to its owner class,
so it should be straightforward to find them.
-->
<f:section title="Hello World Builder">
<f:entry title="French" field="useFrench"
description="Check if we should say hello in French">
<f:checkbox />
</f:entry>
</f:section>
</j:jelly>
After save jenkins is constructing a config file named
examplePlugin.examplePlugin.HelloWorldBuilder.xml
With Content
false
The descriptor itself is the following.
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
#Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
/**
* Descriptor for {#link HelloWorldBuilder}. Used as a singleton.
* The class is marked as public so that it can be accessed from views.
*
* <p>
* See <tt>src/main/resources/hudson/plugins/hello_world/HelloWorldBuilder/*.jelly</tt>
* for the actual HTML fragment for the configuration screen.
*/
#Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
/**
* To persist global configuration information,
* simply store it in a field and call save().
*
* <p>
* If you don't want fields to be persisted, use <tt>transient</tt>.
*/
private boolean useFrench;
/**
* Performs on-the-fly validation of the form field 'name'.
*
* #param value
* This parameter receives the value that the user has typed.
* #return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckName(#QueryParameter String value)
throws IOException, ServletException {
if (value.length() == 0)
return FormValidation.error("Please set a name");
if (value.length() < 4)
return FormValidation.warning("Isn't the name too short?");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Say hello world";
}
#Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
// To persist global configuration information,
// set that to properties and call save().
useFrench = formData.getBoolean("useFrench");
// ^Can also use req.bindJSON(this, formData);
// (easier when there are many fields; need set* methods for this, like setUseFrench)
save();
return super.configure(req,formData);
}
/**
* This method returns true if the global configuration says we should speak French.
*
* The method name is bit awkward because global.jelly calls this method to determine
* the initial state of the checkbox by the naming convention.
*/
public boolean getUseFrench() {
return useFrench;
}
}
Any help with why this is not reloading on reboot would be very helpful, since this seems to be a problem with the example project created by the maven archetype.
So this is problem with the hello world application. You need to define in your constructor that you want to load the configuration.
public DescriptorImpl(){
load();
}
That fixes the issue I was seeing with the configuration not being persisted.

Resources