Giter Site home page Giter Site logo

energywebfoundation / origin Goto Github PK

View Code? Open in Web Editor NEW
103.0 23.0 57.0 144.48 MB

Origin is a set of toolkits that together provide a system for issuance and management of Energy Attribute Certificates

Home Page: https://energyweb.org/technology/ew-origin/

License: MIT License

JavaScript 0.94% TypeScript 97.13% Dockerfile 0.20% Shell 0.28% Makefile 0.22% Solidity 1.22% HTML 0.01%

origin's Introduction


EnergyWeb
EnergyWeb Origin

Origin is a set of toolkits that together provide a system for issuance and management of Energy Attribute Certificates (EACs). This repository is an entry point to Origin systems. It has a goal of explaining briefly the whole system and providing you with insight and info where to explore next.

๐Ÿšง Documentation available at https://energy-web-foundation-origin.readthedocs-hosted.com/en/latest/ ๐Ÿšง

Table of Contents

Packages

SDK Releases

Package Stable Canary Description
@energyweb/origin-device-registry-api npm npm Generic implementation of API working with Origin device registry
@energyweb/origin-device-registry-irec-local-api npm npm API for local version of I-REC compatible registry
@energyweb/origin-energy-api npm npm API for Smart meter reads
@energyweb/origin-organization-irec-api npm npm API for I-REC based organizations
@energyweb/origin-backend npm npm Example backend necessary for running Origin
@energyweb/issuer npm npm Energy Attribute Certificates Issuer Module
@energyweb/issuer-api npm npm NestJS module for interacting with renewable energy certificates
@energyweb/issuer-irec-api npm npm NestJS module for interacting with renewable energy certificates with IREC connectivity
@energyweb/exchange npm npm A service project hosting order book based exchange
@energyweb/exchange-irec npm npm A service project hosting order book based I-REC specific exchange
@energyweb/exchange-core npm npm Generic EACs order book product and matching
@energyweb/exchange-core-irec npm npm An IREC based EACs product and matching
@energyweb/exchange-io-erc1888 npm npm ERC1888 withdwaral/deposit processing for exchange
@energyweb/utils-general npm npm General Utilities
@energyweb/origin-ui-core npm npm React components library for building Origin marketplace user interface
@energyweb/origin-ui-localization npm npm Localization library for building Origin marketplace user interface
@energyweb/origin-ui-theme npm npm Material-UI theme configuration and styling utilities
@energyweb/origin-ui-utils npm npm UI general utilities

Applications, Infrastructure and Demo

Package Description
@energyweb/origin-backend-irec-app Bootstrap project for Origin API that uses I-REC API connection
@energyweb/origin-ui Root of UI for Origin
@energyweb/migrations-irec Deployment and configuration utilities

Packages types

Origin monorepo produce 3 types of the packages that are meant to be used in different use-cases:

Stable

Stable Origin SDK packages are created during release branch build.

Install using yarn add @energyweb/{package}

Canary

Canary packages are created during master branch builds. Canary reflects current state of the master branch, they should be a working versions considers as alpha

Install using yarn add @energyweb/{package}@canary

Preview

Preview packages are built on a special preview branch, this is mostly used as interal tool for tests, demos, discussions.

Install using yarn add @energyweb/{package}@preview

Preparation

  1. Make sure you are using Node 14.x.x
  2. Make sure have latest @microsoft/rush package manager installed.
npm install -g @microsoft/rush
  1. Make sure you have Java runtime installed
  2. Install Postgres 12.x+ and create a new database named origin.

We recommend using Docker based setup as follows (requires psql command line tool installed):

docker pull postgres
docker run --name origin-postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=origin -d -p 5432:5432 postgres
  1. Make sure you have created a .env file in the root of the monorepo and that all necessary variables are set. Use .env.example as an example of how the .env file should look.

  2. Create InfluxDB to store smart meter readings

docker run --rm --env-file ./.env -v $PWD/influxdb-local:/var/lib/influxdb influxdb:1.8 /init-influxdb.sh

Run the InfluxDB instance

docker run --name energy-influxdb --env-file ./.env -d -p 8086:8086 -v $PWD/influxdb-local:/var/lib/influxdb -v $PWD/influxdb.conf:/etc/influxdb/influxdb.conf:ro influxdb:1.8
  1. For custom DB credentials, ports, db name etc refer to https://github.com/energywebfoundation/origin/tree/master/packages/apps/origin-backend-irec-app#development

Installation

rush update

Build

rush build

Test

rush test:e2e

Run demo

After you have the .env file created, installed dependencies (rush install) and build completed (rush build) run the following command:

rush run:origin

Visit the UI at: http://localhost:3000.

Heroku environment provisioning

For fast deployment to Heroku you can run the available script provision-heroku-origin

PREFIX=<name> STAGE=<stage> TEAM=<team> ./provision-heroku-origin.sh

Naming convention is for apps:

${PREFIX}-origin-ui-${STAGE}
${PREFIX}-origin-api-${STAGE}

For e.g in order to create ptt-origin-ui-stable run the script with:

PREFIX=ptt STAGE=stable TEAM=<team> ./provision-heroku-origin.sh

Note: This script assumes that Heroku CLI tool is installed and your are logged in https://devcenter.heroku.com/articles/heroku-cli

Energy Attribute Certificates

Energy Attribute Certificates, or EACs, is an official document which guarantees that produced energy comes from a renewable source. There are different standards that regulate how data is stored and validated. In Europe, this document is called Guarantee of Origin (GO), in North America, it's called Renewable Energy Certificate (REC), and in parts of Asia, Africa, the Middle East, and Latin America governing standard is International REC (I-REC). Standards do vary, but they all share the same core principles.

The main purpose of EACs is to act as an accounting vehicle to prove that consumed energy came from a renewable source. EACs are mostly used to address sustainability reports regarding Scope 2 emissions.

Deployment

For deployment instructions please refer to Deployment wiki page.

Contribution guidelines

If you want to contribute to Origin, be sure to follow classic open source contribution guidelines (described below).

  1. Commiting a change
    • Fork the repository
    • Make a change to repo code
    • Commit the change to the master branch
  2. Pull request

origin's People

Contributors

alexworker23 avatar artursudnik avatar arvindchez avatar atchapcyp avatar chirag-parmar avatar dependabot[bot] avatar driamend avatar e00dan avatar github-actions[bot] avatar grzegorzmatuszaktsh avatar guutong avatar ioncreature avatar jgiter avatar jonathanwfels avatar josipbagaric avatar knzeng-e avatar kosecki123 avatar m0azam avatar makue1105 avatar malak67 avatar marcin-l-tsh avatar patryk-kochanski avatar renesy avatar renovate-bot avatar renovate[bot] avatar shaoddsteam avatar slockitpush avatar soanvig avatar whitneypurdum avatar wjpurdum avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

origin's Issues

"start-all" script not defined in "@energyweb/origin-ui" package

When running the script "run:origin":

"run:origin": "lerna run start-all --scope @energyweb/origin-ui --scope @energyweb/migrations --parallel".

origin-ui does not get initialized because "start-all" script is undefined for the origin-ui package. However, it works perfectly if it's run manually afterwards through "run:ui" that initializes the "start" script for the origin-ui package.

UI - VAT as Required Field

This might be a regulatory related item, but the VAT field on an Org is listed as a required field. US Orgs may not have a VAT. I entered 'None' and all, but maybe the field isn't a "required" field?

Trade is not generated due to priceStrategy is null

https://github.com/energywebfoundation/origin/blob/master/packages/exchange-core/src/MatchingEngine.ts#L282

@energyweb/origin-backend-app: TypeError: Cannot read property 'pickPrice' of null
@energyweb/origin-backend-app:     at /Users/Workspaces/origin/packages/exchange-core/dist/js/src/MatchingEngine.js:214:50
@energyweb/origin-backend-app:     at List.__iterate (/Users/Workspaces/origin/node_modules/immutable/dist/immutable.js:3244:13)
@energyweb/origin-backend-app:     at List.forEach 

I found that pricePickStrategy is string so it always return null
https://github.com/energywebfoundation/origin/blob/master/packages/exchange-core/src/MatchingEngineFactory.ts#L30-L40

Not efficient certificates fetching

Currently the code responsible for fetching certificates uses total request and N events fetching events

export async function getAllCertificates(
    configuration: Configuration.Entity
): Promise<Certificate[]> {
    const { issuer } = configuration.blockchainProperties as Configuration.BlockchainProperties<
        Registry,
        Issuer
    >;
    const totalRequests = (await issuer.totalRequests()).toNumber();

    const certificatePromises = Array(totalRequests)
        .fill(null)
        .map(async (item, index) => {
            const certificationRequestApprovedEvents = await getEventsFromContract(
                issuer,
                issuer.filters.CertificationRequestApproved(null, index + 1, null)
            );

            if (certificationRequestApprovedEvents.length < 1) {
                return null;
            }

            const certId = certificationRequestApprovedEvents[0]._certificateId;
            return certId.gt(0) ? new Certificate(certId.toNumber(), configuration).sync() : null;
        });

    const certificates = await Promise.all(certificatePromises);

    return certificates.filter((cert) => cert !== null);
}

This could be replaced with one call to fetch the IDs based on approved events

const certificationRequestApprovedEvents = await getEventsFromContract(
                issuer,
                issuer.filters.CertificationRequestApproved(null, null, null)
            );

Then new Certificate(id).sync() can be used to return Certificate objects.

Limit exceeded: Query requested more than 10.000 blocks

Get error when try to create certificate request:

0|origin   | [backend] @energyweb/origin-backend-app: [Nest] 854   - 05/06/2021, 1:19:17 PM   [HTTPLoggingInterceptor] 200 | [GET] /api/Device/my-devices?withMeterStats=true - 3ms
0|origin   | [backend] @energyweb/origin-backend-app: [Nest] 854   - 05/06/2021, 1:19:35 PM   [HTTPLoggingInterceptor] 200 | [GET] /api/account - 2ms
0|origin   | [backend] @energyweb/origin-backend-app: [Nest] 854   - 05/06/2021, 1:19:35 PM   [CreateCertificationRequestHandler] Processing certification request 10
0|origin   | [backend] @energyweb/origin-backend-app: [Nest] 854   - 05/06/2021, 1:19:35 PM   [HTTPLoggingInterceptor] 201 | [POST] /api/certification-request - 24ms

0|origin  | [backend] @energyweb/origin-backend-app: [Nest] 854   - 05/06/2021, 1:19:58 PM   [CreateCertificationRequestHandler] Certification request 10 deployment has failed with the error: failed to meet quorum (method="getLogs", params={"filter":{"fromBlock":"0x0","toBlock":"latest","address":"0xac96D06172d2018b7a39281de110E94f13B2EF50","topics":["0x4f043afdb3c4eab4b8ac7438b40e2244d9e936c2ae05175c438cb49e2b796c6a",null,"0x000000000000000000000000000000000000000000000000000000000000000a"]}}, results=[{"weight":1,"start":1620307198298,"error":{"reason":"processing response error","code":"SERVER_ERROR","body":"{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32005,\"message\":\"Limit exceeded: Query requested more than 10.000 blocks\"},\"id\":95}","error":{"code":-32005},"requestBody":"{\"method\":\"eth_getLogs\",\"params\":[{\"fromBlock\":\"0x0\",\"toBlock\":\"latest\",\"address\":\"0xac96d06172d2018b7a39281de110e94f13b2ef50\",\"topics\":[\"0x4f043afdb3c4eab4b8ac7438b40e2244d9e936c2ae05175c438cb49e2b796c6a\",null,\"0x000000000000000000000000000000000000000000000000000000000000000a\"]}],\"id\":95,\"jsonrpc\":\"2.0\"}","requestMethod":"POST","url":"https://volta-rpc.energyweb.org/"}}], provider={"_isProvider":true,"_events":[],"_emitted":{"block":11665018,"t:0xdc43532ab97dea5488a21958d77170a719a62b98b806b9706faeabe1e5ebf52a":11665019},"formatter":{"formats":{"transaction":{},"transactionRequest":{},"receiptLog":{},"receipt":{},"block":{},"blockWithTransactions":{},"filter":{},"filterLog":{}}},"anyNetwork":false,"_networkPromise":{},"_maxInternalBlockNumber":11665018,"_lastBlockNumber":11665018,"_pollingInterval":4000,"_fastQueryDate":1620307194828,"providerConfigs":[{"provider":{"_isProvider":true,"_events":[],"_emitted":{"block":-2},"formatter":{"formats":{"transaction":{},"transactionRequest":{},"receiptLog":{},"receipt":{},"block":{},"blockWithTransactions":{},"filter":{},"filterLog":{}}},"anyNetwork":false,"_networkPromise":{},"_maxInternalBlockNumber":11665019,"_lastBlockNumber":-2,"_pollingInterval":4000,"_fastQueryDate":1620307198614,"connection":{"url":"https://volta-rpc.energyweb.org/"},"_nextId":96,"_network":{"chainId":73799,"name":"unknown"},"_internalBlockNumber":{},"_fastBlockNumber":11665019,"_fastBlockNumberPromise":{}},"weight":1,"stallTimeout":750,"priority":1}],"quorum":0.5,"_highestBlockNumber":11665018,"_network":{"chainId":73799,"name":"unknown"},"_internalBlockNumber":{},"_fastBlockNumber":11665018,"_fastBlockNumberPromise":{},"_poller":null,"_bootstrapPoll":null}, code=SERVER_ERROR, version=providers/5.0.23) +23585ms
Same error, with formating
Certification request 3 deployment has failed with the error: 

failed to meet quorum 

(method="getLogs", 

params=
{"filter":
   {"fromBlock":"0x0",
       "toBlock":"latest",
"address":"0xac96D06172d2018b7a39281de110E94f13B2EF50",
"topics":["0x4f043afdb3c4eab4b8ac7438b40e2244d9e936c2ae05175c438cb49e2b796c6a",
null,
"0x0000000000000000000000000000000000000000000000000000000000000003"]}},

results=
[{"weight":1,
   "start":1620293374409,
"error":
   {"reason":"processing response error",
       "code":"SERVER_ERROR",
"body":"{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32005,\"message\":\"Limit exceeded: Query requested more than 10.000 blocks\"},\"id\":95}",
"error":{"code":-32005},
"requestBody":"{\"method\":\"eth_getLogs\",\"params\":[{\"fromBlock\":\"0x0\",\"toBlock\":\"latest\",\"address\":\"0xac96d06172d2018b7a39281de110e94f13b2ef50\",\"topics\":[\"0x4f043afdb3c4eab4b8ac7438b40e2244d9e936c2ae05175c438cb49e2b796c6a\",null,\"0x0000000000000000000000000000000000000000000000000000000000000003\"]}],\"id\":95,\"jsonrpc\":\"2.0\"}",
"requestMethod":"POST","url":"https://volta-rpc.energyweb.org/"}}],

provider=
{"_isProvider":true,
   "_events":[],
"_emitted":{"block":11663063,
   "t:0x57807ef06ddb141f553a2385bd433e6af224271d54aa6dc4a27a1134fd33e7b3":11663064},
"formatter":{"formats":{"transaction":{},
"transactionRequest":{},
"receiptLog":{},
"receipt":{},
"block":{},
"blockWithTransactions":{},
"filter":{},
"filterLog":{}}},
"anyNetwork":false,
"_networkPromise":{},
"_maxInternalBlockNumber":11663063,
"_lastBlockNumber":11663063,
"_pollingInterval":4000,
"_fastQueryDate":1620293369899,
"providerConfigs":[{"provider":{"_isProvider":true,
   "_events":[],
"_emitted":{"block":-2},
"formatter":{"formats":{"transaction":{},
"transactionRequest":{},
"receiptLog":{},
"receipt":{},
"block":{},
"blockWithTransactions":{},
"filter":{},
"filterLog":{}}},
"anyNetwork":false,
"_networkPromise":{},
"_maxInternalBlockNumber":11663064,
"_lastBlockNumber":-2,
"_pollingInterval":4000,
"_fastQueryDate":1620293374888,
"connection":{"url":"https://volta-rpc.energyweb.org/"},
"_nextId":96,
"_network":{"chainId":73799,
   "name":"unknown"},
"_internalBlockNumber":{},
"_fastBlockNumber":11663064,
"_fastBlockNumberPromise":{}},
"weight":1,"stallTimeout":750,
"priority":1}],"quorum":0.5,
"_highestBlockNumber":11663063,
"_network":{"chainId":73799,
   "name":"unknown"},
"_internalBlockNumber":{},
"_fastBlockNumber":11663063,
"_fastBlockNumberPromise":{},
"_poller":null,
"_bootstrapPoll":null}, 
code=SERVER_ERROR, 
version=providers/5.0.23) +25455ms

p.s. I found some description of this error, but still dont understand why it appear in case of creating sertificate:
image
https://infura.io/docs/ethereum/json-rpc/ratelimits

p.s.2. also, I found in your code that method getLogs located in line 185:
https://github.com/energywebfoundation/origin/blob/7a587a5f2eb6d389cfb1d8dc9427142297bec643/packages/traceability/issuer/src/blockchain-facade/CertificateUtils.ts
and here:
https://github.com/energywebfoundation/origin/blob/7a587a5f2eb6d389cfb1d8dc9427142297bec643/packages/traceability/issuer/src/utils/events.ts

Asked for any help in understanding reasons and ways of fixing.

UI not localizing org users table

Most of the UI is using string lookups to localize output, but in the OrganizationUsersTable.tsx there are some hard-code strings for the table headers:

const columns = [
    { id: 'firstName', label: 'First name' },
    { id: 'lastName', label: 'Last name' },
    { id: 'email', label: 'Email' },
    { id: 'role', label: 'Role' }
];

Question: Fetching Certificates for Device

When we need to fetch Certificates for Device , We are using the helper function from CertificateUtils

CertificateUtils.getAllOwnedCertificates(blockchainProperties)

where in blockchainProperties, we need to set the active user, which is a wallet instance, To get this wallet instance we need to pass the private keys

export interface IBlockchainProperties {
    web3: providers.FallbackProvider | providers.JsonRpcProvider;
    registry: Registry;
    issuer: Issuer;
    activeUser?: Signer;
}

So Is there any other way to fetch the Device certificate, without exposing the device private key?

Issuer approval receiver

There is a mismatch in requesting and approving the requests on issuer.sol contract.

Owner is passed so we can issue for arbitrary address.

function requestCertificationFor(bytes memory _data, address _owner, bool _private) public returns (uint256) {

But approval can overwrite the receiver

) public onlyOwner returns (uint256) {

Seems like we should use request.owner when approving.

Make excludeEnd on DemandTimePeriodService modifiable

const validFrom = Array.from(range.by(diff, { step, excludeEnd: true })).map((v) =>

Currently, If a user wants to create a monthly demand of 2 months user needs to input Jan, 1 - March, 1. Which is not a good experience when frontend app uses a month-picker component (user need to click on Jan, Feb, and March).

I think it will be better if we allow the service caller decide how to adjust the demand period (frontend friendly).

Runtime type error in Demand feature

Currently, We are trying to use Demand feature with boundToGenerationTime set to true and found an error showed below.

@energyweb/origin-backend-app: [Nest] 79826   - 07/01/2020, 3:06:25 PM   [ExceptionsHandler] generationTo.toISOString is not a function +1ms
@energyweb/origin-backend-app: TypeError: generationTo.toISOString is not a function
@energyweb/origin-backend-app:     at /Users/atchapcyp/Repository/ptt-marketplace/origin/packages/exchange/dist/js/src/pods/demand/demand.service.js:131:52
@energyweb/origin-backend-app:     at Array.map (<anonymous>)
@energyweb/origin-backend-app:     at DemandService.prepareBids (/Users/atchapcyp/Repository/ptt-marketplace/origin/packages/exchange/dist/js/src/pods/demand/demand.service.js:119:30)
@energyweb/origin-backend-app:     at DemandService.create (/Users/atchapcyp/Repository/ptt-marketplace/origin/packages/exchange/dist/js/src/pods/demand/demand.service.js:41:35)
@energyweb/origin-backend-app:     at DemandController.create (/Users/atchapcyp/Repository/ptt-marketplace/origin/packages/exchange/dist/js/src/pods/demand/demand.controller.js:39:49)
@energyweb/origin-backend-app:     at /Users/atchapcyp/Repository/ptt-marketplace/origin/node_modules/@nestjs/core/router/router-execution-context.js:38:29

Then, we try to debug and discovered that this line may be the reason for the error.

generationTo: validFrom[i + 1] || createDemand.end

[
   {
    validFrom: 2020-07-01T08:28:37.307Z,
     generationFrom: 2020-07-01T08:28:37.307Z,
     generationTo: 2020-07-08T08:28:37.307Z
   },
   ...
   {
    validFrom: 2020-07-22T08:28:37.307Z,
    generationFrom: 2020-07-22T08:28:37.307Z,
    generationTo: '2020-08-01T08:28:37.307Z'
   }
 ]

The generationTo of the last element seems to have a type of String at runtime.
So I think we need to cast them to Date object somewhere.

Suggestion: Add Dev Auto-Verify Flag

It might be nice to have a "dev" setting in .env which auto-validates both user registrations and org registrations (just force approve status if flag set in the db). This could just help a bit for devs. Just a thought. There's a risk to this being set in production sites though of course, if it is added. A check if in dev mode on app launch would probably be warranted so the flag isn't left active by accident if it's added.

yarn build fails Error: Could not find a compiler version matching ./node_modules/solc. compilers.solc.version option must be a string

โžœ  origin git:(master) โœ— yarn build
yarn run v1.22.10
$ yarn build:static && yarn build:ts && lerna run build --scope @energyweb/origin-ui --stream
$ lerna run build:static --parallel
lerna notice cli v4.0.0
lerna info versioning independent
lerna info Executing command in 5 packages: "yarn run build:static"
@energyweb/exchange-ui-core: $ mkdir -p ./dist/styles/ && cp -r ./src/styles/*.scss ./dist/styles/
@energyweb/origin-ui-core: $ mkdir -p ./dist/styles/ && mkdir -p ./dist/assets/ && cp -r ./src/styles/*.scss ./dist/styles/ && cp -r ./assets/* ./dist/assets/
@energyweb/origin-ui-irec-core: $ mkdir -p ./dist/styles/ && mkdir -p ./dist/assets/ && cp -r ./src/styles/*.scss ./dist/styles/ && cp -r ./assets/* ./dist/assets/
@energyweb/exchange-token-account: $ yarn compile && yarn typechain:ethers
@energyweb/issuer: $ yarn compile && yarn typechain:registry && yarn typechain:issuer
@energyweb/issuer: $ truffle compile
@energyweb/exchange-token-account: $ truffle compile
@energyweb/issuer: Compiling your contracts...
@energyweb/issuer: ===========================
@energyweb/issuer: Error: Could not find a compiler version matching ./node_modules/solc. compilers.solc.version option must be a string specifying:
@energyweb/issuer:    - a path to a locally installed solcjs
@energyweb/issuer:    - a solc version or range (ex: '0.4.22' or '^0.5.0')
@energyweb/issuer:    - a docker image name (ex: 'stable')
@energyweb/issuer:    - 'native' to use natively installed solc
@energyweb/issuer:     at CompilerSupplier.badInputError (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/compilerSupplier/index.js:33:1)
@energyweb/issuer:     at CompilerSupplier.load (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/compilerSupplier/index.js:75:1)
@energyweb/issuer:     at loadParser (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/profiler/loadParser.js:15:29)
@energyweb/issuer:     at Object.requiredSources (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/profiler/index.js:19:1)
@energyweb/issuer:     at Object.sourcesWithDependencies (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/index.js:68:45)
@energyweb/issuer:     at necessary (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/index.js:42:1)
@energyweb/issuer:     at /Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/workflow-compile/index.js:38:1
@energyweb/issuer:     at async Promise.all (index 0)
@energyweb/issuer:     at compile (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/workflow-compile/index.js:28:1)
@energyweb/issuer:     at Object.compile (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/workflow-compile/index.js:71:47)
@energyweb/issuer:     at Object.run (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/core/lib/commands/compile.js:86:1)
@energyweb/issuer:     at Command.run (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/core/lib/command.js:140:1)
@energyweb/issuer: Truffle v5.3.3 (core: 5.3.3)
@energyweb/issuer: Node v14.16.1
@energyweb/issuer: error Command failed with exit code 1.
@energyweb/issuer: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
@energyweb/issuer: error Command failed with exit code 1.
@energyweb/issuer: info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
lerna ERR! yarn run build:static exited 1 in '@energyweb/issuer'
lerna ERR! yarn run build:static stdout:
$ yarn compile && yarn typechain:registry && yarn typechain:issuer
$ truffle compile

Compiling your contracts...
===========================
Error: Could not find a compiler version matching ./node_modules/solc. compilers.solc.version option must be a string specifying:
   - a path to a locally installed solcjs
   - a solc version or range (ex: '0.4.22' or '^0.5.0')
   - a docker image name (ex: 'stable')
   - 'native' to use natively installed solc

    at CompilerSupplier.badInputError (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/compilerSupplier/index.js:33:1)
    at CompilerSupplier.load (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/compilerSupplier/index.js:75:1)
    at loadParser (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/profiler/loadParser.js:15:29)
    at Object.requiredSources (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/profiler/index.js:19:1)
    at Object.sourcesWithDependencies (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/index.js:68:45)
    at necessary (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/compile-solidity/index.js:42:1)
    at /Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/workflow-compile/index.js:38:1
    at async Promise.all (index 0)
    at compile (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/workflow-compile/index.js:28:1)
    at Object.compile (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/workflow-compile/index.js:71:47)
    at Object.run (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/core/lib/commands/compile.js:86:1)
    at Command.run (/Users/dev-d/1-WorkspaceSlockit/ew-nve/test/origin/node_modules/truffle/build/webpack:/packages/core/lib/command.js:140:1)
Truffle v5.3.3 (core: 5.3.3)
Node v14.16.1
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
lerna ERR! yarn run build:static stderr:
error Command failed with exit code 1.
error Command failed with exit code 1.
lerna ERR! yarn run build:static exited 1 in '@energyweb/issuer'
lerna WARN complete Waiting for 1 child process to exit. CTRL-C to exit immediately.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Unable to connect to the database.

After typing yarn build I get the following error:

 [Nest] 44818   - 01/04/2021, 2:00:04 PM   [ExceptionHandler] Unable to connect to the database. Retrying (1)...
@energyweb/origin-organization-irec-api-client: error: password authentication failed for user "postgres"

Yarn version: 1.22.5
Psql version: (PostgreSQL) 12.5

I followed the guide (Run Demo)

Maybe I did something wrong with the .env.example file (?)

Origin not able to connect to blockchain network using Metamask extension

Based on the documentation, I was trying to bootstrap origin application (backend, frontend, ganache) on my machine using yarn run:origin. Application boots up without any errors but as long as I access URL http://localhost:3000/devices/production, Metamask extension asks to connect to Blockchain network which is running on http://localhost:8545/ (as a part of yarn run command)
I have imported all the accounts on Metamask by providing seed phrase from ganache-cli running locally. But UI shows Please check your blockchain network and connect to correct and web console throws below error

sagas.js:205 ContractsSaga::WrongNetwork Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
    at ABICoder.../../node_modules/web3-eth-contract/node_modules/web3-eth-abi/src/index.js.ABICoder.decodeParameters (index.js:226)
    at Contract.../../node_modules/web3-eth-contract/src/index.js.Contract._decodeMethodReturn (index.js:471)
    at Method.outputFormatter (index.js:824)
    at Method.../../node_modules/web3-eth-contract/node_modules/web3-core-method/src/index.js.Method.formatOutput (index.js:165)
    at sendTxCallback (index.js:540)
    at index.js:147
    at inpage.js:1
    at inpage.js:1
    at i (inpage.js:1)
    at inpage.js:1

Can you let me know which step am I missing here?

Addition of new line in DeviceFacades.test.ts breaks build

Hi @kosecki123 I'm new to this project and I just checked out master. The test DeviceFacades.test.ts doesn't compile due to a line you added in your latest PR:

import { DeviceClient } from '@energyweb/origin-device-registry-irec-form-api-client';

How do we get the path of this registered?

Can I see token transfers that happen in Origin UI via block-explorer (or via graphiql query ) ?

I found in your confluence article that show how to create query requests:
https://energyweb.atlassian.net/wiki/spaces/EWF/pages/708608094/The+Blockexplorer

Also, I found in https://volta-explorer.energyweb.org/graphiql requests type that can show token transfers of GO tokens :
image
image
But when I create this type of request - I get response: internal server error (in both networks: Volta and main network)

here to see example or request: (spoiiler)

click spoiiler

1. I found transaction:
0xd3529254d1c44b5226dd9cb32cc42581aeae3b0fe34ef3923f834e8e84e97dcb

image

2. inside transaction I found token contract address:

0xB7fe98b5487CED6053729821edFAb1Db3DED53Ff
image

3. after that I create request:
image

Rush update issue

Hello i am trying use energy web origin but I come up with the showed in the image. I was wondering if anybody else encounter this issues and resolved it. I have been using the following to setup energy web origin https://github.com/energywebfoundation/origin. I get the following issue:

### ERROR: Internal Error: Unable to find dependency @nestjs/schedule with version 0.4.3 in shrinkwrap.
You have encountered a software defect. Please consider reporting the issue to the maintainers of this application.

I am currently communicating with the rush team with the following ticket: microsoft/rushstack#2768

Issues when running the deployment

Hi everyone, first of all, I want to say that I love this project and wanted to test for a while, struggling a little bit. I'm willing to deploy Origin in an AWS EC2 instance but firstly I'm testing it locally.

I have issues with step 4 of the Deployment tutorial (Frontend), after running docker-compose up -d --build I'm getting this:

ERROR: for origin_nginx_1 Cannot start service nginx: OCI runtime create failed: container_linux.go:349: starting container process caused "process_linux.go:449: container init caused \"rootfs_linux.go:58: mounting \\\"/home/madog/Documents/repos/samples/ewf/origin/packages/origin-ui/nginx/default.conf\\\" to rootfs \\\"/var/snap/docker/common/var-lib-docker/overlay2/5a8dc50ebf28a291a6e0b4a884f4afb79a623d0319479d4f43a86aafd42a10b6/merged\\\" at \\\"/var/snap/docker/common/var-lib-docker/overlay2/5a8dc50ebf28a291a6e0b4a884f4afb79a623d0319479d4f43a86aafd42a10b6/merged/etc/nginx/conf.d/default.conf\\\" caused \\\"not a directory\\\"\"": unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type

ERROR: for nginx Cannot start service nginx: OCI runtime create failed: container_linux.go:349: starting container process caused "process_linux.go:449: container init caused \"rootfs_linux.go:58: mounting \\\"/home/madog/Documents/repos/samples/ewf/origin/packages/origin-ui/nginx/default.conf\\\" to rootfs \\\"/var/snap/docker/common/var-lib-docker/overlay2/5a8dc50ebf28a291a6e0b4a884f4afb79a623d0319479d4f43a86aafd42a10b6/merged\\\" at \\\"/var/snap/docker/common/var-lib-docker/overlay2/5a8dc50ebf28a291a6e0b4a884f4afb79a623d0319479d4f43a86aafd42a10b6/merged/etc/nginx/conf.d/default.conf\\\" caused \\\"not a directory\\\"\"": unknown: Are you trying to mount a directory onto a file (or vice-versa)? Check if the specified host path exists and is the expected type ERROR: Encountered errors while bringing up the project.

I'm trying to debug this through docker documentation but I'm wondering if any of you had this issue and is yes, how did you solve it?

Thanks in advance, cheers!

New User Reg (Perhaps an Issue)

A newly registered user is prompted (actually forced) to register a new org on first registration. However, if you register, and then immediately logout/login, you are not (again) forced to register a new org. You can still do so, but it's now out of the thread I think the site expected.

Users With Multiple Roles

If you have a user with rights of multiple roles (e.g. 17), the organizations -> members UI page crashes. thx.

Screen Shot 2021-03-23 at 9 06 37 AM

UI Resets Multiple Roles to Single Role

You can't create a user with multiple roles in the UI, and if they have multiple roles already in the DB, when you edit their role(s) in the UI, it will delete all roles except the new one entered.

Perhaps this is by design? (users forced to only have one role, but if so, the db structure doesn't really match that design decision).

Here's a VS code-workspace file

Here's an origin.code-workspace file for VS Code if you want to use it (remove .txt extension and place in root of repo), if desired.
origin.code-workspace.txt

Edit: Updated the file a bit to group items by Server/Client. VS Code doesn't allow nested folders.

Global ENERGY_PER_UNIT usage

#1080 introduced a global variable called ENERGY_PER_UNIT which defines the amount of energy in single certificate in Wh for e.g 1000000 for 1MWh certificates.

This variable is currently used only in the @energyweb/exchange package, but should be used globally to avoid unknown errors and discrepancies.

Coin integration

Is there any js-sdk of energy web token for transaction available?

I want to integrate coin in OPOLO hardware wallet.

node-pre-gyp ERR error

In the new version with node 14.0.0 I am getting the following error after typing yarn:

node-pre-gyp ERR! cwd /home/origin/node_modules/sqlite3
node-pre-gyp ERR! node -v v14.0.0
node-pre-gyp ERR! node-pre-gyp -v v0.11.0
node-pre-gyp ERR! not ok 

I had to update some things in the code and change the node to version 14.x.x After that I got an error

First, I tried:

rm yarn.lock && yarn

yarn upgrade

I've cleared the cache and the error still occur (yarn cache clean)

Also tried in this order:

    rm yarn.lock
    yarn cache clean
    yarn

I think that my version of the grpc library is old and is not compatible with that version of Node, so I tried:

npm install grpc --build-from-source

I will add that the older version works fine.
How can I solve it?

Not optimal balance check.

Current implementation for getting balance per user is unnecessarily complex.

private async calculateOwnership(): Promise<IShareInCertificate> {

Instead of this the better option would be:

  • scan for transfers and batch transfers with your address
  • take id from those events
  • use 1155.balanceOfBatch to resolve balances

Same possibly can be applied to getting claimed balance.

Release fails

Releasing Origin fails with the following error:
https://github.com/energywebfoundation/origin/runs/2165161553#step:11:80


lerna ERR! Error: Command failed: git commit -F /tmp/295b7033-2f7d-40b5-8ffc-dc8e3ef86794/lerna-commit.txt
lerna ERR! Author identity unknown
lerna ERR! 
lerna ERR! *** Please tell me who you are.
lerna ERR! 
lerna ERR! Run
lerna ERR! 
lerna ERR!   git config --global user.email "[email protected]"
lerna ERR!   git config --global user.name "Your Name"
lerna ERR! 
lerna ERR! to set your account's default identity.
lerna ERR! Omit --global to set the identity only in this repository.
lerna ERR! 
lerna ERR! fatal: empty ident name (for <runner@fv-az235-449.5pzow1yype5elkuvz1yqqwk3sf.xx.internal.cloudapp.net>) not allowed
lerna ERR! 
lerna ERR!     at makeError (/home/runner/work/origin/origin/node_modules/execa/index.js:174:9)
lerna ERR!     at /home/runner/work/origin/origin/node_modules/execa/index.js:278:16
lerna ERR!     at runMicrotasks (<anonymous>)
lerna ERR!     at processTicksAndRejections (internal/process/task_queues.js:93:5)
lerna ERR! lerna Command failed: git commit -F /tmp/295b7033-2f7d-40b5-8ffc-dc8e3ef86794/lerna-commit.txt
lerna ERR! lerna Author identity unknown
lerna ERR! lerna 
lerna ERR! lerna *** Please tell me who you are.
lerna ERR! lerna 
lerna ERR! lerna Run
lerna ERR! lerna 
lerna ERR! lerna   git config --global user.email "[email protected]"
lerna ERR! lerna   git config --global user.name "Your Name"
lerna ERR! lerna 
lerna ERR! lerna to set your account's default identity.
lerna ERR! lerna Omit --global to set the identity only in this repository.
lerna ERR! lerna 
lerna ERR! lerna fatal: empty ident name (for <runner@fv-az235-449.5pzow1yype5elkuvz1yqqwk3sf.xx.internal.cloudapp.net>) not allowed
lerna ERR! lerna 
error Command failed with exit code 128.lerna ERR! Error: Command failed: git commit -F /tmp/295b7033-2f7d-40b5-8ffc-dc8e3ef86794/lerna-commit.txt
lerna ERR! Author identity unknown
lerna ERR! 
lerna ERR! *** Please tell me who you are.
lerna ERR! 
lerna ERR! Run
lerna ERR! 
lerna ERR!   git config --global user.email "[email protected]"
lerna ERR!   git config --global user.name "Your Name"
lerna ERR! 
lerna ERR! to set your account's default identity.
lerna ERR! Omit --global to set the identity only in this repository.
lerna ERR! 
lerna ERR! fatal: empty ident name (for <runner@fv-az235-449.5pzow1yype5elkuvz1yqqwk3sf.xx.internal.cloudapp.net>) not allowed
lerna ERR! 
lerna ERR!     at makeError (/home/runner/work/origin/origin/node_modules/execa/index.js:174:9)
lerna ERR!     at /home/runner/work/origin/origin/node_modules/execa/index.js:278:16
lerna ERR!     at runMicrotasks (<anonymous>)
lerna ERR!     at processTicksAndRejections (internal/process/task_queues.js:93:5)
lerna ERR! lerna Command failed: git commit -F /tmp/295b7033-2f7d-40b5-8ffc-dc8e3ef86794/lerna-commit.txt
lerna ERR! lerna Author identity unknown
lerna ERR! lerna 
lerna ERR! lerna *** Please tell me who you are.
lerna ERR! lerna 
lerna ERR! lerna Run
lerna ERR! lerna 
lerna ERR! lerna   git config --global user.email "[email protected]"
lerna ERR! lerna   git config --global user.name "Your Name"
lerna ERR! lerna 
lerna ERR! lerna to set your account's default identity.
lerna ERR! lerna Omit --global to set the identity only in this repository.
lerna ERR! lerna 
lerna ERR! lerna fatal: empty ident name (for <runner@fv-az235-449.5pzow1yype5elkuvz1yqqwk3sf.xx.internal.cloudapp.net>) not allowed
lerna ERR! lerna 
error Command failed with exit code 128.

There was an error compiling your contract: Experimental features are turned on. Do not use experimental features on live deployments. --> Can't validate Origin smart-contract Registry.sol (that located on 'release' branch)

After using this tutorial
https://docs.blockscout.com/for-users/smart-contract-interaction/verifying-a-smart-contract
I prepared smart-contract from release branch
https://github.com/energywebfoundation/origin/blob/release/packages/traceability/issuer/contracts/Registry.sol

https://volta-explorer.energyweb.org/address/0x56c343e525A157DC5472D63E7D4Ca606F6F41C92/contract_verifications/new

and try to validate it, but get error :
There was an error compiling your contract: Experimental features are turned on. Do not use experimental features on live deployments.
(I think that error happened because of line 2 in Registry.sol, that enabled experimental features : pragma experimental ABIEncoderV2;)

image



Click here to see smart-contract that I try to validate
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol

pragma solidity ^0.5.0;


/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
  /**
   * @dev Returns the addition of two unsigned integers, reverting on
   * overflow.
   *
   * Counterpart to Solidity's `+` operator.
   *
   * Requirements:
   * - Addition cannot overflow.
   */
  function add(uint256 a, uint256 b) internal pure returns (uint256) {
      uint256 c = a + b;
      require(c >= a, "SafeMath: addition overflow");

      return c;
  }

  /**
   * @dev Returns the subtraction of two unsigned integers, reverting on
   * overflow (when the result is negative).
   *
   * Counterpart to Solidity's `-` operator.
   *
   * Requirements:
   * - Subtraction cannot overflow.
   */
  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
      return sub(a, b, "SafeMath: subtraction overflow");
  }

  /**
   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
   * overflow (when the result is negative).
   *
   * Counterpart to Solidity's `-` operator.
   *
   * Requirements:
   * - Subtraction cannot overflow.
   *
   * _Available since v2.4.0._
   */
  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
      require(b <= a, errorMessage);
      uint256 c = a - b;

      return c;
  }

  /**
   * @dev Returns the multiplication of two unsigned integers, reverting on
   * overflow.
   *
   * Counterpart to Solidity's `*` operator.
   *
   * Requirements:
   * - Multiplication cannot overflow.
   */
  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
      // benefit is lost if 'b' is also tested.
      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
      if (a == 0) {
          return 0;
      }

      uint256 c = a * b;
      require(c / a == b, "SafeMath: multiplication overflow");

      return c;
  }

  /**
   * @dev Returns the integer division of two unsigned integers. Reverts on
   * division by zero. The result is rounded towards zero.
   *
   * Counterpart to Solidity's `/` operator. Note: this function uses a
   * `revert` opcode (which leaves remaining gas untouched) while Solidity
   * uses an invalid opcode to revert (consuming all remaining gas).
   *
   * Requirements:
   * - The divisor cannot be zero.
   */
  function div(uint256 a, uint256 b) internal pure returns (uint256) {
      return div(a, b, "SafeMath: division by zero");
  }

  /**
   * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
   * division by zero. The result is rounded towards zero.
   *
   * Counterpart to Solidity's `/` operator. Note: this function uses a
   * `revert` opcode (which leaves remaining gas untouched) while Solidity
   * uses an invalid opcode to revert (consuming all remaining gas).
   *
   * Requirements:
   * - The divisor cannot be zero.
   *
   * _Available since v2.4.0._
   */
  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
      // Solidity only automatically asserts when dividing by 0
      require(b > 0, errorMessage);
      uint256 c = a / b;
      // assert(a == b * c + a % b); // There is no case in which this doesn't hold

      return c;
  }

  /**
   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
   * Reverts when dividing by zero.
   *
   * Counterpart to Solidity's `%` operator. This function uses a `revert`
   * opcode (which leaves remaining gas untouched) while Solidity uses an
   * invalid opcode to revert (consuming all remaining gas).
   *
   * Requirements:
   * - The divisor cannot be zero.
   */
  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
      return mod(a, b, "SafeMath: modulo by zero");
  }

  /**
   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
   * Reverts with custom message when dividing by zero.
   *
   * Counterpart to Solidity's `%` operator. This function uses a `revert`
   * opcode (which leaves remaining gas untouched) while Solidity uses an
   * invalid opcode to revert (consuming all remaining gas).
   *
   * Requirements:
   * - The divisor cannot be zero.
   *
   * _Available since v2.4.0._
   */
  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
      require(b != 0, errorMessage);
      return a % b;
  }
}

// File: @openzeppelin/upgrades/contracts/Initializable.sol

pragma solidity >=0.4.24;


/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {

/**
 * @dev Indicates that the contract has been initialized.
 */
bool private initialized;

/**
 * @dev Indicates that the contract is in the process of being initialized.
 */
bool private initializing;

/**
 * @dev Modifier to use in the initializer function of a contract.
 */
modifier initializer() {
  require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");

  bool isTopLevelCall = !initializing;
  if (isTopLevelCall) {
    initializing = true;
    initialized = true;
  }

  _;

  if (isTopLevelCall) {
    initializing = false;
  }
}

/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
  // extcodesize checks the size of the code stored in an address, and
  // address returns the current address. Since the code is still not
  // deployed when running a constructor, any checks on its code size will
  // yield zero, making it an effective way to detect if a contract is
  // under construction or not.
  address self = address(this);
  uint256 cs;
  assembly { cs := extcodesize(self) }
  return cs == 0;
}

// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}

// File: @openzeppelin/contracts-ethereum-package/contracts/introspection/IERC165.sol

pragma solidity ^0.5.0;

/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
  /**
   * @dev Returns true if this contract implements the interface defined by
   * `interfaceId`. See the corresponding
   * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
   * to learn more about how these ids are created.
   *
   * This function call must use less than 30 000 gas.
   */
  function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: @openzeppelin/contracts-ethereum-package/contracts/introspection/ERC165.sol

pragma solidity ^0.5.0;



/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is Initializable, IERC165 {
  /*
   * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
   */
  bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;

  /**
   * @dev Mapping of interface ids to whether or not it's supported.
   */
  mapping(bytes4 => bool) private _supportedInterfaces;

  function initialize() public initializer {
      // Derived contracts need only register support for their own interfaces,
      // we register support for ERC165 itself here
      _registerInterface(_INTERFACE_ID_ERC165);
  }

  /**
   * @dev See {IERC165-supportsInterface}.
   *
   * Time complexity O(1), guaranteed to always use less than 30 000 gas.
   */
  function supportsInterface(bytes4 interfaceId) public view returns (bool) {
      return _supportedInterfaces[interfaceId];
  }

  /**
   * @dev Registers the contract as an implementer of the interface defined by
   * `interfaceId`. Support of the actual ERC165 interface is automatic and
   * registering its interface id is not required.
   *
   * See {IERC165-supportsInterface}.
   *
   * Requirements:
   *
   * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
   */
  function _registerInterface(bytes4 interfaceId) internal {
      require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
      _supportedInterfaces[interfaceId] = true;
  }

  uint256[50] private ______gap;
}

// File: contracts/ERC1155/Address.sol

pragma solidity ^0.5.0;


/**
* Utility library of inline functions on addresses
*/
library Address {

  /**
   * Returns whether the target address is a contract
   * @dev This function will return false if invoked during the constructor of a contract,
   * as the code is not actually created until after the constructor finishes.
   * @param account address of the account to check
   * @return whether the target address is a contract
   */
  function isContract(address account) internal view returns (bool) {
      uint256 size;
      // XXX Currently there is no better way to check if there is a contract in an address
      // than to check the size of the code at that address.
      // See https://ethereum.stackexchange.com/a/14016/36603
      // for more details about how this works.
      // TODO Check this again before the Serenity release, because all addresses will be
      // contracts then.
      // solium-disable-next-line security/no-inline-assembly
      assembly { size := extcodesize(account) }
      return size > 0;
  }

}

// File: contracts/ERC1155/Common.sol

pragma solidity ^0.5.0;

/**
  Note: Simple contract to use as base for const vals
*/
contract CommonConstants {

  bytes4 constant internal ERC1155_ACCEPTED = 0xf23a6e61; // bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))
  bytes4 constant internal ERC1155_BATCH_ACCEPTED = 0xbc197c81; // bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))
}

// File: contracts/ERC1155/IERC1155TokenReceiver.sol

pragma solidity ^0.5.0;

/**
  Note: The ERC-165 identifier for this interface is 0x4e2312e0.
*/
interface ERC1155TokenReceiver {
  /**
      @notice Handle the receipt of a single ERC1155 token type.
      @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated.
      This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer.
      This function MUST revert if it rejects the transfer.
      Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
      @param _operator  The address which initiated the transfer (i.e. msg.sender)
      @param _from      The address which previously owned the token
      @param _id        The ID of the token being transferred
      @param _value     The amount of tokens being transferred
      @param _data      Additional data with no specified format
      @return           `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
  */
  function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4);

  /**
      @notice Handle the receipt of multiple ERC1155 token types.
      @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated.
      This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s).
      This function MUST revert if it rejects the transfer(s).
      Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller.
      @param _operator  The address which initiated the batch transfer (i.e. msg.sender)
      @param _from      The address which previously owned the token
      @param _ids       An array containing ids of each token being transferred (order and length must match _values array)
      @param _values    An array containing amounts of each token being transferred (order and length must match _ids array)
      @param _data      Additional data with no specified format
      @return           `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
  */
  function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4);
}

// File: contracts/ERC1155/IERC1155.sol

pragma solidity ^0.5.0;

/**
  @title ERC-1155 Multi Token Standard
  @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md
  Note: The ERC-165 identifier for this interface is 0xd9b67a26.
*/
interface IERC1155 /* is ERC165 */ {
  /**
      @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
      The `_operator` argument MUST be msg.sender.
      The `_from` argument MUST be the address of the holder whose balance is decreased.
      The `_to` argument MUST be the address of the recipient whose balance is increased.
      The `_id` argument MUST be the token type being transferred.
      The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
      When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
      When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
  */
  event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value);

  /**
      @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
      The `_operator` argument MUST be msg.sender.
      The `_from` argument MUST be the address of the holder whose balance is decreased.
      The `_to` argument MUST be the address of the recipient whose balance is increased.
      The `_ids` argument MUST be the list of tokens being transferred.
      The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
      When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
      When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
  */
  event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values);

  /**
      @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled).
  */
  event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);

  /**
      @dev MUST emit when the URI is updated for a token ID.
      URIs are defined in RFC 3986.
      The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
  */
  event URI(string _value, uint256 indexed _id);

  /**
      @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
      @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
      MUST revert if `_to` is the zero address.
      MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
      MUST revert on any other error.
      MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
      After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
      @param _from    Source address
      @param _to      Target address
      @param _id      ID of the token type
      @param _value   Transfer amount
      @param _data    Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
  */
  function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;

  /**
      @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
      @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
      MUST revert if `_to` is the zero address.
      MUST revert if length of `_ids` is not the same as length of `_values`.
      MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
      MUST revert on any other error.
      MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
      Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
      After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
      @param _from    Source address
      @param _to      Target address
      @param _ids     IDs of each token type (order and length must match _values array)
      @param _values  Transfer amounts per token type (order and length must match _ids array)
      @param _data    Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
  */
  function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external;

  /**
      @notice Get the balance of an account's Tokens.
      @param _owner  The address of the token holder
      @param _id     ID of the Token
      @return        The _owner's balance of the Token type requested
   */
  function balanceOf(address _owner, uint256 _id) external view returns (uint256);

  /**
      @notice Get the balance of multiple account/token pairs
      @param _owners The addresses of the token holders
      @param _ids    ID of the Tokens
      @return        The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
   */
  function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);

  /**
      @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
      @dev MUST emit the ApprovalForAll event on success.
      @param _operator  Address to add to the set of authorized operators
      @param _approved  True if the operator is approved, false to revoke approval
  */
  function setApprovalForAll(address _operator, bool _approved) external;

  /**
      @notice Queries the approval status of an operator for a given owner.
      @param _owner     The owner of the Tokens
      @param _operator  Address of authorized operator
      @return           True if the operator is approved, false if not
  */
  function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}

// File: contracts/ERC1155/ERC1155.sol

pragma solidity ^0.5.0;







// A sample implementation of core ERC1155 function.
contract ERC1155 is IERC1155, ERC165, CommonConstants
{
  using SafeMath for uint256;
  using Address for address;

  // id => (owner => balance)
  mapping (uint256 => mapping(address => uint256)) internal balances;

  // owner => (operator => approved)
  mapping (address => mapping(address => bool)) internal operatorApproval;

/////////////////////////////////////////// ERC165 //////////////////////////////////////////////

  /*
      bytes4(keccak256('supportsInterface(bytes4)'));
  */
  bytes4 constant private INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7;

  /*
      bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^
      bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^
      bytes4(keccak256("balanceOf(address,uint256)")) ^
      bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^
      bytes4(keccak256("setApprovalForAll(address,bool)")) ^
      bytes4(keccak256("isApprovedForAll(address,address)"));
  */
  bytes4 constant private INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26;

  function supportsInterface(bytes4 _interfaceId)
  public
  view
  returns (bool) {
       if (_interfaceId == INTERFACE_SIGNATURE_ERC165 ||
           _interfaceId == INTERFACE_SIGNATURE_ERC1155) {
          return true;
       }

       return false;
  }

/////////////////////////////////////////// ERC1155 //////////////////////////////////////////////

  /**
      @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
      @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
      MUST revert if `_to` is the zero address.
      MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
      MUST revert on any other error.
      MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
      After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
      @param _from    Source address
      @param _to      Target address
      @param _id      ID of the token type
      @param _value   Transfer amount
      @param _data    Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
  */
  function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) public {

      require(_to != address(0x0), "safeTransferFrom: _to must be non-zero.");
      require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");
      require(balances[_id][_from] > 0, "safeTransferFrom: _from balance has to be higher than 0");

      // SafeMath will throw with insuficient funds _from
      // or if _id is not valid (balance will be 0)
      balances[_id][_from] = balances[_id][_from].sub(_value);
      balances[_id][_to] = _value.add(balances[_id][_to]);

      // MUST emit event
      emit TransferSingle(msg.sender, _from, _to, _id, _value);

      // Now that the balance is updated and the event was emitted,
      // call onERC1155Received if the destination is a contract.
      if (_to.isContract()) {
          _doSafeTransferAcceptanceCheck(msg.sender, _from, _to, _id, _value, _data);
      }
  }

  /**
      @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
      @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
      MUST revert if `_to` is the zero address.
      MUST revert if length of `_ids` is not the same as length of `_values`.
      MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
      MUST revert on any other error.
      MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
      Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
      After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
      @param _from    Source address
      @param _to      Target address
      @param _ids     IDs of each token type (order and length must match _values array)
      @param _values  Transfer amounts per token type (order and length must match _ids array)
      @param _data    Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
  */
  function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) public {

      // MUST Throw on errors
      require(_to != address(0x0), "destination address must be non-zero.");
      require(_ids.length == _values.length, "_ids and _values array lenght must match.");
      require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "Need operator approval for 3rd party transfers.");

      for (uint256 i = 0; i < _ids.length; ++i) {
          uint256 id = _ids[i];
          uint256 value = _values[i];

          // SafeMath will throw with insuficient funds _from
          // or if _id is not valid (balance will be 0)
          balances[id][_from] = balances[id][_from].sub(value);
          balances[id][_to]   = value.add(balances[id][_to]);
      }

      // Note: instead of the below batch versions of event and acceptance check you MAY have emitted a TransferSingle
      // event and a subsequent call to _doSafeTransferAcceptanceCheck in above loop for each balance change instead.
      // Or emitted a TransferSingle event for each in the loop and then the single _doSafeBatchTransferAcceptanceCheck below.
      // However it is implemented the balance changes and events MUST match when a check (i.e. calling an external contract) is done.

      // MUST emit event
      emit TransferBatch(msg.sender, _from, _to, _ids, _values);

      // Now that the balances are updated and the events are emitted,
      // call onERC1155BatchReceived if the destination is a contract.
      if (_to.isContract()) {
          _doSafeBatchTransferAcceptanceCheck(msg.sender, _from, _to, _ids, _values, _data);
      }
  }

  /**
      @notice Get the balance of an account's Tokens.
      @param _owner  The address of the token holder
      @param _id     ID of the Token
      @return        The _owner's balance of the Token type requested
   */
  function balanceOf(address _owner, uint256 _id) external view returns (uint256) {
      // The balance of any account can be calculated from the Transfer events history.
      // However, since we need to keep the balances to validate transfer request,
      // there is no extra cost to also privide a querry function.
      return balances[_id][_owner];
  }


  /**
      @notice Get the balance of multiple account/token pairs
      @param _owners The addresses of the token holders
      @param _ids    ID of the Tokens
      @return        The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair)
   */
  function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory) {

      require(_owners.length == _ids.length);

      uint256[] memory balances_ = new uint256[](_owners.length);

      for (uint256 i = 0; i < _owners.length; ++i) {
          balances_[i] = balances[_ids[i]][_owners[i]];
      }

      return balances_;
  }

  /**
      @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
      @dev MUST emit the ApprovalForAll event on success.
      @param _operator  Address to add to the set of authorized operators
      @param _approved  True if the operator is approved, false to revoke approval
  */
  function setApprovalForAll(address _operator, bool _approved) external {
      operatorApproval[msg.sender][_operator] = _approved;
      emit ApprovalForAll(msg.sender, _operator, _approved);
  }

  /**
      @notice Queries the approval status of an operator for a given owner.
      @param _owner     The owner of the Tokens
      @param _operator  Address of authorized operator
      @return           True if the operator is approved, false if not
  */
  function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
      return operatorApproval[_owner][_operator];
  }

/////////////////////////////////////////// Internal //////////////////////////////////////////////

  function _doSafeTransferAcceptanceCheck(address _operator, address _from, address _to, uint256 _id, uint256 _value, bytes memory _data) internal {

      // If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
      // the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.


      // Note: if the below reverts in the onERC1155Received function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
      // If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_ACCEPTED test.
      require(ERC1155TokenReceiver(_to).onERC1155Received(_operator, _from, _id, _value, _data) == ERC1155_ACCEPTED, "contract returned an unknown value from onERC1155Received");
  }

  function _doSafeBatchTransferAcceptanceCheck(address _operator, address _from, address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) internal {

      // If this was a hybrid standards solution you would have to check ERC165(_to).supportsInterface(0x4e2312e0) here but as this is a pure implementation of an ERC-1155 token set as recommended by
      // the standard, it is not necessary. The below should revert in all failure cases i.e. _to isn't a receiver, or it is and either returns an unknown value or it reverts in the call to indicate non-acceptance.

      // Note: if the below reverts in the onERC1155BatchReceived function of the _to address you will have an undefined revert reason returned rather than the one in the require test.
      // If you want predictable revert reasons consider using low level _to.call() style instead so the revert does not bubble up and you can revert yourself on the ERC1155_BATCH_ACCEPTED test.
      require(ERC1155TokenReceiver(_to).onERC1155BatchReceived(_operator, _from, _ids, _values, _data) == ERC1155_BATCH_ACCEPTED, "contract returned an unknown value from onERC1155BatchReceived");
  }
}

// File: contracts/ERC1155/ERC1155Mintable.sol

pragma solidity ^0.5.0;


/**
  @dev Mintable form of ERC1155
  Shows how easy it is to mint new items.
*/
contract ERC1155Mintable is ERC1155 {

  bytes4 constant private INTERFACE_SIGNATURE_URI = 0x0e89341c;

  // id => creators
  mapping (uint256 => address) public creators;

  // A nonce to ensure we have a unique id each time we mint.
  uint256 public nonce;

  modifier creatorOnly(uint256 _id) {
      require(creators[_id] == msg.sender);
      _;
  }

  function supportsInterface(bytes4 _interfaceId)
  public
  view
  returns (bool) {
      if (_interfaceId == INTERFACE_SIGNATURE_URI) {
          return true;
      } else {
          return super.supportsInterface(_interfaceId);
      }
  }

  // Creates a new token type and assigns _initialSupply to minter
  function create(uint256 _initialSupply, string calldata _uri, address creator) external returns(uint256 _id) {

      _id = ++nonce;
      creators[_id] = creator;
      balances[_id][creator] = _initialSupply;

      // require(balances[_id][creator] > 0, "balance not increased");

      // Transfer event with mint semantic
      emit TransferSingle(creator, address(0x0), creator, _id, _initialSupply);

      if (bytes(_uri).length > 0)
          emit URI(_uri, _id);
  }

  // Mint tokens. Assign directly to _to.
  function mint(uint256 _id, address _to, uint256 _quantity) external creatorOnly(_id) {

      // Grant the items to the caller
      balances[_id][_to] = _quantity.add(balances[_id][_to]);

      // Emit the Transfer/Mint event.
      // the 0x0 source address implies a mint
      // It will also provide the circulating supply info.
      emit TransferSingle(msg.sender, address(0x0), _to, _id, _quantity);

      if (_to.isContract()) {
          _doSafeTransferAcceptanceCheck(msg.sender, msg.sender, _to, _id, _quantity, '');
      }
  }

  function setURI(string calldata _uri, uint256 _id) external creatorOnly(_id) {
      emit URI(_uri, _id);
  }
}

// File: contracts/ERC1888/IERC1888.sol

pragma solidity ^0.5.6;
pragma experimental ABIEncoderV2;

interface ERC1888 {

  struct Certificate {
      int256 topic;
      address issuer; // msg.sender
      bytes validityData; // call data
      bytes data;
  }

  event IssuanceSingle(address indexed _issuer, int256 indexed _topic, uint256 _id);
  //event IssuanceBatch(address indexed _issuer, int256[] indexed _topics, uint256[] _ids);

  event ClaimSingle(address indexed _claimIssuer, address indexed _claimSubject, int256 indexed _topic, uint256 _id, uint256 _value, bytes _claimData);
  event ClaimBatch(address indexed _claimIssuer, address indexed _claimSubject, int256[] indexed _topics, uint256[] _ids, uint256[] _values, bytes[] _claimData);

  function issue(address _to, bytes calldata _validityData, int256 _topic, uint256 _value, bytes calldata _data) external returns (uint256);
  // function batchIssue(bytes[]   _data, uint256[]   _topics, uint256[]   _value, bytes32[]   _signatures) external returns(uint256[]);

  function safeTransferAndClaimFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data, bytes calldata _claimData) external;
  function safeBatchTransferAndClaimFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data, bytes[] calldata _claimData) external;

  function getCertificate(uint256 _id) external view returns (address issuer, int256 topic, bytes memory validityCall, bytes memory data);
  function claimedBalanceOf(address _owner, uint256 _id) external view returns (uint256);
  // function claimedBalanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory);
}

// File: contracts/Registry.sol

pragma solidity ^0.5.6;
pragma experimental ABIEncoderV2;



contract Registry is ERC1155Mintable, ERC1888 {

  mapping(uint256 => Certificate) public certificateStorage;
  mapping(uint256 => mapping(address => uint256)) public claimedBalances;

  // Array with all certificate ids, used for enumeration
  uint256[] private _allCertificates;
  // Mapping from certificate id to position in the allCertificates array
  mapping(uint256 => uint256) private _allCertificatesIndex;

  function issue(address _to, bytes calldata _validityData, int256 _topic, uint256 _value, bytes calldata _data) external returns (uint256 _id) {
  	_validate(msg.sender, _validityData);

  	_id = this.create(_value, "Certificate", msg.sender);

  	if (_value > 0) {
  		safeTransferFrom(msg.sender, _to, _id, _value, _data);
  	}

  	certificateStorage[_id] = Certificate({
  		topic: _topic,
  		issuer: msg.sender,
  		validityData: _validityData,
  		data: _data
  	});

  	_allCertificatesIndex[_id] = _allCertificates.length;
  	_allCertificates.push(_id);

  	emit IssuanceSingle(msg.sender, _topic, _id);
  }

  function safeTransferAndClaimFrom(
  	address _from,
  	address _to,
  	uint256 _id,
  	uint256 _value,
  	bytes calldata _data,
  	bytes calldata _claimData
  ) external {
  	Certificate memory cert = certificateStorage[_id];

  	_validate(cert.issuer,  cert.validityData);

      require(_to != address(0x0), "safeTransferAndClaimFrom: _to must be non-zero.");
      require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "safeTransferAndClaimFrom: Need operator approval for 3rd party claims.");
      require(balances[_id][_from] > 0, "safeTransferAndClaimFrom: _from balance has to be higher than 0");

  	if (_from != _to) {
  		safeTransferFrom(_from, _to, _id, _value, _data);
  	}

  	_burn(_to, _id, _value);

  	emit ClaimSingle(_from, _to, cert.topic, _id, _value, _claimData); //_claimSubject address ??
  }

  function safeBatchTransferAndClaimFrom(
  	address _from,
  	address _to,
  	uint256[] calldata _ids,
  	uint256[] calldata _values,
  	bytes calldata _data,
  	bytes[] calldata _claimData
  ) external {
  	uint numberOfClaims = _ids.length;

      require(_to != address(0x0), "safeBatchTransferAndClaimFrom: _to address must be non-zero.");
      require(_ids.length == _values.length, "safeBatchTransferAndClaimFrom: _ids and _values array length must match.");
      require(_from == msg.sender || operatorApproval[_from][msg.sender] == true, "safeBatchTransferAndClaimFrom: Need operator approval for 3rd party transfers.");

  	require(numberOfClaims > 0, "safeBatchTransferAndClaimFrom: at least one certificate has to be present.");
  	require(
  		_values.length == numberOfClaims && _claimData.length == numberOfClaims,
  		"safeBatchTransferAndClaimFrom: not all arrays are of the same length."
  	);

  	int256[] memory topics = new int256[](numberOfClaims);

  	for (uint256 i = 0; i < numberOfClaims; ++i) {
  		Certificate memory cert = certificateStorage[_ids[i]];
  		_validate(cert.issuer,  cert.validityData);
  		topics[i] = cert.topic;
  	}

  	if (_from != _to) {
  		safeBatchTransferFrom(_from, _to, _ids, _values, _data);
  	}

  	for (uint256 i = 0; i < numberOfClaims; ++i) {
  		_burn(_to, _ids[i], _values[i]);
  	}

  	emit ClaimBatch(_from, _to, topics, _ids, _values, _claimData);
  }

  function getCertificate(uint256 _id) external view returns (address issuer, int256 topic, bytes memory validityData, bytes memory data) {
  	require(_id <= totalSupply(), "getCertificate: _id out of bounds");

  	Certificate memory certificate = certificateStorage[_id];
  	return (certificate.issuer, certificate.topic, certificate.validityData, certificate.data);
  }

  function claimedBalanceOf(address _owner, uint256 _id) external view returns (uint256) {
  	return claimedBalances[_id][_owner];
  }

  function _burn(address _from, uint256 _id, uint256 _value) internal {
  	balances[_id][_from] = balances[_id][_from].sub(_value);
  	claimedBalances[_id][_from] = claimedBalances[_id][_from].add(_value);
  }

  function _validate(address _verifier, bytes memory _validityData) internal view {
  	if (_verifier.isContract()) {
  		(bool success, bytes memory result) = _verifier.staticcall(_validityData);

  		require(
  			success && abi.decode(result, (bool)),
  			"_validate(): Request/certificate invalid, please check with your issuer."
  		);
      }
  }

  /**
   * @dev Gets the total amount of certificates stored by the contract.
   * @return uint256 representing the total amount of certificates
   */
  function totalSupply() public view returns (uint256) {
      return _allCertificates.length;
  }

  function allCertificateIds() public view returns (uint256[] memory) {
  	return _allCertificates;
  }
}


Also, I try to fix this error in few different ways, but every time get new errors and no final luck.

Can I get any advice about error that I get ?
(or may be there is some place where I can found smart-contract for release branch that is ready to pass "verify & publish" step ? )

P.S.
Also, I found release notes of Solidity 0.8 that inform about ABI coder v2 is activated by default. https://docs.soliditylang.org/en/v0.8.0/080-breaking-changes.html
But I can not use 0.8.x version of compiler due validation because of restriction from first line of code:
pragma solidity ^0.5.6;
that is in Registry.sol contract on release branch.
(Looks like that compiler version that I can use is limited up to 0.6.0)

also, If I try to change version of compiler - I get error There was an error compiling your contract: Source file requires different compiler version (current compiler is 0.8.4+commit.c7e474f2.Emscripten.clang) - note that nightly builds are considered to be strictly less than the released version

Matching engine order status management

#763 exposed a weakness in current order status management via matching engine.

Looks like some statuses are mixing two different things: order status in matching engine and order status based on the executed volume. As such matching engine should not manage status for executed volume anymore, it's sufficient to have updated volume to operate.

Removal of volume based statuses allows us to implement order reactivation required by demand pause/resume in the correct way.

Can't find any example orders

I tried to take a look in the origin marketplace in the demo version, but it's always empty.

How can I read the asks and bids from the marketplace?

Thanks in advance!

Org Approve UI Issue

on Mac Chrome, the approve for a submitted org is "up a line" (not on the proper org line) Will try to capture a screenshot...

Use auth/authorization mechanism in exchange tests

Currently exchange e2e tests using mocks for auth and roles guards making it not reliable for tests that want to check the permissions.

The solution is to use auth module from origin-backend and setup tests in exchange project.

Suggest enhancing chain address verification

e.g. in BlockchainAddresses.tsx, etc. to:

const VALIDATION_SCHEMA = Yup.object().shape({
blockchainAccountAddress: Yup.string()
.label(t('user.properties.blockchainAddress'))
.test(
t('user.properties.blockchainAddress'),
t('user.validationMessages.invalidBlockchainAddress'),
function (value) {
return ethers.utils.isAddress(value);
}
)
});

Origin not able to connect to blockchain network using Metamask extension

In continuation of the earlier issue #642 I am still facing the same issue Please make sure you've chosen the correct blockchain network and the contract address is valid. using local ganache network. I am using below setup

  1. node version : v12.16.1
  2. npm : 6.13.4
  3. solc version: 0.5.0+commit.1d4f565a.Darwin.appleclang
  4. solcjs version: 0.5.16+commit.9c3226ce.Emscripten.clang
  5. Metamask to connect ganache running on localhost:8545
  6. I have manually imported all accounts on metamask while initial boot-up of ganache-cli using yarn run:ganache
  7. commands to bootstrap application as you suggested in following sequence
    • yarn run:ganache
    • yarn run:backend
    • yarn run:demo
    • yarn run:ui

After this I get this error message on console even after switching the network from localhost to mainnet many times.

bundle.js:451877 ContractsSaga::WrongNetwork Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
    at ABICoder.../../node_modules/web3-eth-contract/node_modules/web3-eth-abi/src/index.js.ABICoder.decodeParameters (bundle.js:216412)
    at Contract.../../node_modules/web3-eth-contract/src/index.js.Contract._decodeMethodReturn (bundle.js:218443)
    at Method.outputFormatter (bundle.js:218796)
    at Method.../../node_modules/web3-eth-contract/node_modules/web3-core-method/src/index.js.Method.formatOutput (bundle.js:215148)
    at sendTxCallback (bundle.js:215523)
    at bundle.js:210761
    at inpage.js:1
    at inpage.js:1
    at i (inpage.js:1)
    at inpage.js:1

Can you please suggest what's going wrong?

Gas price calculation rounding error

Description

  • When calculating the gas price, the service results always 0 for slow, standard and fast. It seems that there's a problem when rounding a very small value here.

This is the current return of the station:

{
"health": true,
"block_number": 8532236,
"block_time": 5.176,
"slow": 0,
"standard": 0,
"fast": 0,
"instant": 97
}

Note: Tried to open the issue on gas price repo but seems that the issues sections is not active there so I created it here

small typo (english ui)

change:

Thanks for registering a user on the marketplace

to:

Thanks for registering as a user on the marketplace

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Suggestion - Small Readme Update

Suggest now adding to Readme in Running just so users know it's there also:

To start Origin using Volta Testnet Web3:

yarn run:origin:web3

Note: maybe add link to newly added RTD Volta setup info also.

Relase-B-Volta-Deployment-(before-Monorepo) - Deployment to Volta Failed

This is in regards to the https://github.com/energywebfoundation/origin/wiki/Relase-B-Volta-Deployment-(before-Monorepo)

My deployment is failing with Origin UI giving me the error..
index.js?bbaf:226 Uncaught (in promise) Error: Returned values aren't valid, did it run Out of Gas?

It seems ew-utils-demo-master did not start correctly.
The coresponding logs are as below..
verbose: Got off chain properties from http://0.0.0.0:3030/ConsumingAsset/0
verbose: Consuming asset 0 synced

sleep

info: Certificates for Asset #0 initialized


/home/ubuntu/buffalogap/ew-utils-demo-master/node_modules/ew-asset-registry-lib/
const outputResult = r.result.output;
^

TypeError: Cannot read property 'output' of undefined

The URL http://0.0.0.0:3030 is coming from API_BASE_URL under ew-utils-demo-master/src/config.ts

What should be the value of API_BASE_URL?
Are there any other additional configurations beyond connection-config.json?
I am using the default accounts already defined under config/contractConfig.json for Volta deployment. Is that fine?

Generation time in Order and Asset tables in Postgre are always generated as current date

Reproduce steps:

  1. Request for certificate with Generation time 1st - 30th Apr 2020.
  2. After certificate is created, do publish for sale.

Screen Shot 2563-04-16 at 16 18 34

Result

  • In Asset, the generationFrom and generationTo are 16th Apr (current date)

Screen Shot 2563-04-16 at 16 20 31

  • In Order, the product has the generationFrom and generationTo as 15th Apr

Screen Shot 2563-04-16 at 16 22 30

Expected

  • Should the generationTime in Asset and Order be the same as the generationTime in the certificate?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.